Example #1
0
def export_submitted_coa(country=None, chart=None):
    """
		Make charts tree and export submitted charts as .json files
		to public/files/submitted_charts
		:param country: Country name is optional
	"""

    path = os.path.join(os.path.abspath(frappe.get_site_path()), "public",
                        "files", "submitted_charts")
    frappe.create_folder(path)

    filters = {"submitted": 1}
    if country:
        filters.update({"country": country})
    if chart:
        filters.update({"name": chart})

    company_for_submitted_charts = frappe.get_all(
        "Company", filters, ["name", "country", "chart_of_accounts_name"])

    for company in company_for_submitted_charts:
        account_tree = get_account_tree_from_existing_company(company.name)
        write_chart_to_file(account_tree, company, path)

    make_tarfile(
        path, company_for_submitted_charts[0].chart_of_accounts_name or chart)
Example #2
0
def copy_files_to_visit(dms_file_list, visit_id, profile_id, pid, req_id):
	import os, shutil, glob
	for loc in dms_file_list:

		path_lst = loc.get('file_location')[0].split('/') if len(loc.get('file_location')) > 0 else loc.get('text_file_loc').split('/')
		
		file_path = os.path.join('/'.join(path_lst[0:len(path_lst)-1]), visit_id)
		
		frappe.create_folder(file_path)

		for filename in glob.glob(os.path.join('/'.join(path_lst[0:len(path_lst)-1]), '*.*')):
			if profile_id != pid:
				base_path = file_path.split('/files/')[1].split('/')
				base_path[0] = pid
				if req_id:
					print ['testing for multifile upload',req_id]
					base_path.insert(1, req_id)	
					req = frappe.get_doc('Shared Requests', req_id)
					event_dict = json.loads(req.event_dict)
					sub_event_count = json.loads(req.sub_event_count)
					shared_file_count('/'.join(base_path)[:-1], event_dict, sub_event_count, 3, 4)

					req.event_dict = json.dumps(event_dict)
					req.sub_event_count = json.dumps(sub_event_count)

					req.save()

				provider_path = os.path.join(file_path.split('/files/')[0], 'files', '/'.join(base_path)[:-1])
				frappe.create_folder(provider_path)
				shutil.copy(filename, provider_path)

			shutil.move(filename, file_path)
Example #3
0
def make_error_snapshot(exception):
	if frappe.conf.disable_error_snapshot:
		return

	logger = frappe.logger(with_more_info=True)

	try:
		error_id = "{timestamp:s}-{ip:s}-{hash:s}".format(
			timestamp=cstr(datetime.datetime.now()),
			ip=frappe.local.request_ip or "127.0.0.1",
			hash=frappe.generate_hash(length=3),
		)
		snapshot_folder = get_error_snapshot_path()
		frappe.create_folder(snapshot_folder)

		snapshot_file_path = os.path.join(snapshot_folder, "{0}.json".format(error_id))
		snapshot = get_snapshot(exception)

		with open(encode(snapshot_file_path), "wb") as error_file:
			error_file.write(encode(frappe.as_json(snapshot)))

		logger.error("New Exception collected with id: {}".format(error_id))

	except Exception as e:
		logger.error("Could not take error snapshot: {0}".format(e), exc_info=True)
Example #4
0
def make_error_snapshot(exception):
    if frappe.conf.disable_error_snapshot:
        return

    logger = frappe.get_logger()

    try:
        error_id = '{timestamp:s}-{ip:s}-{hash:s}'.format(
            timestamp=cstr(datetime.datetime.now()),
            ip=frappe.local.request_ip or '127.0.0.1',
            hash=frappe.generate_hash(length=3))
        snapshot_folder = get_error_snapshot_path()
        frappe.create_folder(snapshot_folder)

        snapshot_file_path = os.path.join(snapshot_folder,
                                          "{0}.json".format(error_id))
        snapshot = get_snapshot(exception)

        with open(encode(snapshot_file_path), 'wb') as error_file:
            error_file.write(encode(frappe.as_json(snapshot)))

        logger.error('New Exception collected with id: {}'.format(error_id))

    except Exception, e:
        logger.error('Could not take error snapshot: {0}'.format(e))
	def make_thumbnail(self, file_url, doc, dn):
		try:
			image = Image.open(StringIO.StringIO(self.content))
			filename, extn = file_url.rsplit(".", 1)
		except IOError:
				frappe.msgprint("Unable to read file format for {0}".format(os.path.realpath(self.file_path)))
				return

		thumbnail = ImageOps.fit(
			image,
			(300, 300),
			Image.ANTIALIAS
		)

		thumbnail_url = filename + "." + extn

		path = os.path.abspath(frappe.get_site_path("public", thumbnail_url.lstrip("/")))

		frappe.create_folder(os.path.dirname(path))

		try:
			thumbnail.save(path)
			doc.db_set("thumbnail_url", thumbnail_url)
		except IOError:
			frappe.msgprint("Unable to write file format for {0}".format(path))
def create_new_connection(module, connection_name):
    if not frappe.conf.get("developer_mode"):
        frappe.msgprint(
            _("Please enable developer mode to create new connection"))
        return
    # create folder
    module_path = frappe.get_module_path(module)
    connectors_folder = os.path.join(module_path, "connectors")
    frappe.create_folder(connectors_folder)

    # create init py
    create_init_py(module_path, "connectors", "")

    connection_class = connection_name.replace(" ", "")
    file_name = frappe.scrub(connection_name) + ".py"
    file_path = os.path.join(module_path, "connectors", file_name)

    # create boilerplate file
    with open(file_path, "w") as f:
        f.write(
            connection_boilerplate.format(connection_class=connection_class))

    # get python module string from file_path
    app_name = frappe.db.get_value("Module Def", module, "app_name")
    python_module = os.path.relpath(file_path,
                                    "../apps/{0}".format(app_name)).replace(
                                        os.path.sep, ".")[:-3]

    return python_module
Example #7
0
def image_writter(profile_id, event_id=None, visit_id=None):
	import os, base64
	data = {"profile_id": profile_id, "event_id": event_id, "visit_id": visit_id}
	filelist = get_image_details(data)
	for file_obj in filelist:
		
		tags = file_obj.get('tag_id').split('-')[2]
		folder = tag_dict.get(tags[:2])
		sub_folder = sub_tag_dict.get(tags[:2]).get(tags[2:])
		path = os.path.join(os.getcwd(), get_site_path().replace('.',"").replace('/', ""), 'public', 'files', data.get('profile_id'), data.get("event_id"),  folder, sub_folder, file_obj.get('visit_id'))
		
		wfile_name = file_obj.get('temp_file_id').split('.')[0] + '-watermark.' + file_obj.get('temp_file_id').split('.')[1]
		if not os.path.exists(os.path.join(path, wfile_name)):
			frappe.create_folder(path)
			img_path = os.path.join(path,  wfile_name)
			frappe.errprint(["visit_id", data.get('visit_id')])
			data = {
				"entityid": file_obj.get('visit_id'),
				"profile_id": data.get('profile_id'),
				"event_id": data.get("event_id") or "",
				"tag_id": file_obj.get('tag_id'),
				"file_id": [
					file_obj.get('temp_file_id')
				],
				"file_location": [
					img_path
				]
			}
			res = write_file(data)
def create_new_connection(module, connection_name):
    if not frappe.conf.get('developer_mode'):
        frappe.msgprint(
            _('Please enable developer mode to create new connection'))
        return
    # create folder
    module_path = frappe.get_module_path(module)
    connectors_folder = os.path.join(module_path, 'connectors')
    frappe.create_folder(connectors_folder)

    # create init py
    create_init_py(module_path, 'connectors', '')

    connection_class = connection_name.replace(' ', '')
    file_name = frappe.scrub(connection_name) + '.py'
    file_path = os.path.join(module_path, 'connectors', file_name)

    # create boilerplate file
    with open(file_path, 'w') as f:
        f.write(
            connection_boilerplate.format(connection_class=connection_class))

    # get python module string from file_path
    app_name = frappe.db.get_value('Module Def', module, 'app_name')
    python_module = os.path.relpath(file_path,
                                    '../apps/{0}'.format(app_name)).replace(
                                        os.path.sep, '.')[:-3]

    return python_module
Example #9
0
def write_docfile(data):
	import os
	for indx, file_path in enumerate(data.get('files')):
		base_dir_path = os.path.join(os.getcwd(), get_site_path().replace('.',"").replace('/', ""), 'public', 'files')
		folder_lst = file_path.split('/')
		file_path =  '/'.join(folder_lst[:-1]) 
		doc_name = folder_lst[-1:][0]
		doc_base_path = os.path.join(base_dir_path, file_path)

		if '-watermark' not in doc_name:
			dname = doc_name.split('.')
			doc_name = dname[0]+'-watermark.'+dname[1]

		data.get('files')[indx] = "{doc_base_path}/{doc_name}".format(doc_base_path=doc_base_path, doc_name=doc_name)

		if not os.path.exists(doc_base_path + '/' +doc_name):
			frappe.create_folder(doc_base_path)
			data = {
				"entityid": folder_lst[4],
				"profile_id": folder_lst[0],
				"event_id": folder_lst[1],
				"tag_id": folder_lst[4] + '-' + cstr(folder_lst[2].split('-')[1]) + cstr(folder_lst[3].split('_')[1]),
				"file_id": [
					doc_name.replace('-watermark','')
				],
				"file_location": [
					doc_base_path + '/' + doc_name
				]
			}

			from templates.pages.event import write_file
			res = write_file(data)
Example #10
0
def get_pdf_site_path(profile_id, folder, sub_folder, event_id, timestamp):
    site_path = os.path.join(os.getcwd(),
                             get_site_path().replace('.', "").replace('/', ""),
                             'public', 'files')
    path = os.path.join(site_path, profile_id, event_id, folder, sub_folder)
    frappe.create_folder(path)
    return {'site_path': site_path, 'timestamp': timestamp, 'path': path}
Example #11
0
def get_patient_data(data):
	dms_files = []
	filelist = frappe.db.sql("select files_list from `tabShared Requests` where name = '%s'"%data.get('other_param').get('req_id'), as_list=1)[0][0]
	filelist = json.loads(filelist)

	data_dict ={"to_profile_id":data.get('profile_id'),
		"received_from": "desktop", "from_profile_id": data.get('other_param').get('patient_profile_id'),
		"event_tag_id": data.get('other_param').get('event_id')}

	for fl in filelist:
		fl = fl.split('files/')[1].split('/')
		file_dict = {"entityid": fl[4],
			"profile_id": fl[0],
			"event_id": fl[1]}

		file_dict['tag_id'] = fl[4] + '-' +  fl[2].split('-')[1] + fl[3].split('_')[1]
		file_dict["file_id"] = [fl[5].replace('-watermark', '')]

		file_dict['file_location'] = [os.path.join(os.getcwd(), get_site_path().replace('.',"")
									.replace('/', ""), 'public', 'files',
									data_dict.get('to_profile_id'),
									data.get('other_param').get('req_id'), fl[1], fl[2], fl[3], fl[4])]

		frappe.create_folder(file_dict['file_location'][0])

		file_dict['file_location'] = [file_dict['file_location'][0] + '/' + file_dict["file_id"][0]]

		if not  os.path.exists(file_dict['file_location'][0]):
			dms_files.append(file_dict)

		request_type="POST"
		url="%s/dms/getvisitmultiplefile"%get_base_url()
		from phr.phr.phr_api import get_response
		param = {"filelist": dms_files}
		response=get_response(url, json.dumps(param), request_type)
	def make_thumbnail(self, file_url, doc, dn):
		try:
			image = Image.open(StringIO.StringIO(self.content))
			filename, extn = file_url.rsplit(".", 1)
		except IOError:
				frappe.msgprint("Unable to read file format for {0}".format(os.path.realpath(self.file_path)))
				return

		thumbnail = ImageOps.fit(
			image,
			(300, 300),
			Image.ANTIALIAS
		)

		thumbnail_url = filename + "." + extn

		path = os.path.abspath(frappe.get_site_path("public", thumbnail_url.lstrip("/")))

		frappe.create_folder(os.path.dirname(path))

		try:
			thumbnail.save(path)
			doc.db_set("thumbnail_url", thumbnail_url)
		except IOError:
			frappe.msgprint("Unable to write file format for {0}".format(path))
Example #13
0
def image_writter(profile_id, event_id=None, visit_id=None):
    import os, base64
    data = {
        "profile_id": profile_id,
        "event_id": event_id,
        "visit_id": visit_id
    }
    filelist = get_image_details(data)
    for file_obj in filelist:

        tags = file_obj.get('tag_id').split('-')[2]
        folder = tag_dict.get(tags[:2])
        sub_folder = sub_tag_dict.get(tags[:2]).get(tags[2:])
        path = os.path.join(os.getcwd(),
                            get_site_path().replace('.', "").replace('/', ""),
                            'public', 'files', data.get('profile_id'),
                            data.get("event_id"), folder, sub_folder,
                            file_obj.get('visit_id'))

        wfile_name = file_obj.get('temp_file_id').split('.')[
            0] + '-watermark.' + file_obj.get('temp_file_id').split('.')[1]
        if not os.path.exists(os.path.join(path, wfile_name)):
            frappe.create_folder(path)
            img_path = os.path.join(path, wfile_name)
            frappe.errprint(["visit_id", data.get('visit_id')])
            data = {
                "entityid": file_obj.get('visit_id'),
                "profile_id": data.get('profile_id'),
                "event_id": data.get("event_id") or "",
                "tag_id": file_obj.get('tag_id'),
                "file_id": [file_obj.get('temp_file_id')],
                "file_location": [img_path]
            }
            res = write_file(data)
Example #14
0
def make_error_snapshot(exception):
	if frappe.conf.disable_error_snapshot:
		return

	logger = frappe.get_logger()

	try:
		error_id = '{timestamp:s}-{ip:s}-{hash:s}'.format(
			timestamp=cstr(datetime.datetime.now()),
			ip=frappe.local.request_ip or '127.0.0.1',
			hash=frappe.generate_hash(length=3)
		)
		snapshot_folder = get_error_snapshot_path()
		frappe.create_folder(snapshot_folder)

		snapshot_file_path = os.path.join(snapshot_folder, "{0}.json".format(error_id))
		snapshot = get_snapshot(exception)

		with open(encode(snapshot_file_path), 'wb') as error_file:
			error_file.write(encode(frappe.as_json(snapshot)))

		logger.error('New Exception collected with id: {}'.format(error_id))

	except Exception, e:
		logger.error('Could not take error snapshot: {0}'.format(e))
def create_invoice_pdf(sinv, fid, iuser):
    file_path = get_files_path("portal-files")
    frappe.create_folder(file_path)
    output = PdfFileWriter()
    output = frappe.get_print("Sales Invoice",
                              sinv,
                              "standard",
                              as_pdf=True,
                              output=output)
    file = os.path.join(file_path, "{0}.pdf".format(fid))
    output.write(open(file, "wb"))
    frappe.publish_realtime(event="invoice_ready",
                            message={
                                "sub": sinv,
                                "dict": {
                                    "bgCompleted": 1,
                                    "fid": fid
                                }
                            },
                            user=iuser)
    frappe.publish_realtime("new_notifications", {
        "type":
        "default",
        "message":
        "PDF for Invoice# {sub} is available to download.".format(sub=sinv)
    },
                            user=iuser)
Example #16
0
def write_docfile(data):
    import os
    for file_path in data.get('files'):
        base_dir_path = os.path.join(
            os.getcwd(),
            get_site_path().replace('.', "").replace('/', ""), 'public',
            'files')
        folder_lst = file_path.split('/')
        file_path = '/'.join(folder_lst[:-1])
        doc_name = folder_lst[-1:][0]
        doc_base_path = os.path.join(base_dir_path, file_path)

        if not os.path.exists(doc_base_path + '/' + doc_name):
            frappe.create_folder(doc_base_path)
            data = {
                "entityid":
                folder_lst[4],
                "profile_id":
                folder_lst[0],
                "event_id":
                folder_lst[1],
                "tag_id":
                folder_lst[4] + '-' + cstr(folder_lst[2].split('-')[1]) +
                cstr(folder_lst[3].split('_')[1]),
                "file_id": [doc_name.replace('-watermark', '')],
                "file_location": [doc_base_path + '/' + doc_name]
            }

            from templates.pages.event import write_file
            res = write_file(data)
def create_new_connection(module, connection_name):
	if not frappe.conf.get('developer_mode'):
		frappe.msgprint(_('Please enable developer mode to create new connection'))
		return
	# create folder
	module_path = frappe.get_module_path(module)
	connectors_folder = os.path.join(module_path, 'connectors')
	frappe.create_folder(connectors_folder)

	# create init py
	create_init_py(module_path, 'connectors', '')

	connection_class = connection_name.replace(' ', '')
	file_name = frappe.scrub(connection_name) + '.py'
	file_path = os.path.join(module_path, 'connectors', file_name)

	# create boilerplate file
	with open(file_path, 'w') as f:
		f.write(connection_boilerplate.format(connection_class=connection_class))

	# get python module string from file_path
	app_name = frappe.db.get_value('Module Def', module, 'app_name')
	python_module = os.path.relpath(
		file_path, '../apps/{0}'.format(app_name)).replace(os.path.sep, '.')[:-3]

	return python_module
def write_file(content, file_path, fname):
	"""write file to disk with a random name (to compare)"""
	# create directory (if not exists)
	frappe.create_folder(get_files_path())
	# write the file
	with open(os.path.join(file_path.encode('utf-8'), fname.encode('utf-8')), 'w+') as f:
		f.write(content)
	return get_files_path(fname)
Example #19
0
def delete_vcards():  # TODO: make def delete_vcards_in_address_book()
    address_book_folder = get_vdirsyncer_address_book_path(
    )  # TODO: Ask for address_book to delete. Using default

    shutil.rmtree(address_book_folder)  # Deleting Entire Folder
    frappe.create_folder(address_book_folder,
                         with_init=False)  # Create Folder Again
    return {}
Example #20
0
def write_file(content, file_path, fname):
    """write file to disk with a random name (to compare)"""
    # create directory (if not exists)
    frappe.create_folder(get_files_path())
    # write the file
    with open(os.path.join(file_path, fname), 'w+') as f:
        f.write(content)
    return get_files_path(fname)
Example #21
0
def get_pdf_site_path(profile_id, folder, sub_folder, event_id, timestamp):
	site_path = os.path.join(os.getcwd(), get_site_path().replace('.',"").replace('/', ""), 'public', 'files')
	path = os.path.join(site_path, profile_id, event_id, folder, sub_folder)
	frappe.create_folder(path)
	return {
		'site_path': site_path,
		'timestamp': timestamp 
	}
Example #22
0
def share_dm(data, header, share_info, profile_id, disease):
    share_info = json.loads(share_info)
    frappe.create_folder(os.path.join(get_files_path(), profile_id))
    save_pdf(data, header, profile_id, disease)

    if share_info.get('share_via') == 'Email':
        return send_email(share_info, profile_id, disease)
    else:
        return share_via_phr(share_info, profile_id, disease)
Example #23
0
def write_translations_file(app, lang, full_dict=None):
    app_messages = get_messages_for_app(app)
    if not app_messages:
        return

    tpath = frappe.get_pymodule_path(app, "translations")
    frappe.create_folder(tpath)
    write_csv_file(os.path.join(tpath, lang + ".csv"), app_messages, full_dict
                   or get_full_dict(lang))
Example #24
0
def share_dm(data, header, share_info, profile_id, disease):
	share_info = json.loads(share_info)
	frappe.create_folder(os.path.join(get_files_path() , profile_id))
	save_pdf(data, header, profile_id, disease)

	if share_info.get('share_via') == 'Email':
		return send_email(share_info, profile_id, disease)
	else:
		return share_via_phr(share_info, profile_id, disease)
Example #25
0
def get_vdirsyncer_path(*path, is_folder=True):
    folder_path = frappe.utils.get_bench_path(
    ) + '/sites/' + frappe.get_site_path('private', 'vdirsyncer', *path)[2:]

    if is_folder:
        frappe.create_folder(
            folder_path, with_init=False)  # Create Directory (if not exists)

    return folder_path
Example #26
0
def get_html_reports_path(report_name,
                          where="reports",
                          hash=None,
                          localsite=None):
    site = localsite or frappe.local.site
    path_jasper_module = os.path.dirname(jasper_erpnext_report.__file__)
    path = os.path.join(path_jasper_module, "public", where, site, report_name,
                        hash)
    frappe.create_folder(path)
    return path
Example #27
0
def make_site_config(db_name=None, db_password=None, site_config=None):
	frappe.create_folder(os.path.join(frappe.local.site_path))
	site_file = get_site_config_path()

	if not os.path.exists(site_file):
		if not (site_config and isinstance(site_config, dict)):
			site_config = get_conf_params(db_name, db_password)

		with open(site_file, "w") as f:
			f.write(json.dumps(site_config, indent=1, sort_keys=True))
Example #28
0
def make_site_config(db_name=None, db_password=None, site_config=None):
    frappe.create_folder(os.path.join(frappe.local.site_path))
    site_file = get_site_config_path()

    if not os.path.exists(site_file):
        if not (site_config and isinstance(site_config, dict)):
            site_config = get_conf_params(db_name, db_password)

        with open(site_file, "w") as f:
            f.write(json.dumps(site_config, indent=1, sort_keys=True))
Example #29
0
def write_file(content, fname, is_private=0):
    """write file to disk with a random name (to compare)"""
    file_path = get_files_path(is_private=is_private)

    # create directory (if not exists)
    frappe.create_folder(file_path)
    # write the file
    with open(os.path.join(file_path.encode("utf-8"), fname.encode("utf-8")), "w+") as f:
        f.write(content)

    return get_files_path(fname, is_private=is_private)
Example #30
0
def write_file(content, files_path):
    """write file to disk with a random name (to compare)"""
    # create account folder (if not exists)
    frappe.create_folder(files_path)
    fname = os.path.join(files_path, frappe.generate_hash())

    # write the file
    with open(fname, 'w+') as f:
        f.write(content)

    return fname
Example #31
0
def write_translations_file(app, lang, full_dict=None, app_messages=None):
	if not app_messages:
		app_messages = get_messages_for_app(app)

	if not app_messages:
		return

	tpath = frappe.get_pymodule_path(app, "translations")
	frappe.create_folder(tpath)
	write_csv_file(os.path.join(tpath, lang + ".csv"),
		app_messages, full_dict or get_full_dict(lang))
Example #32
0
def write_file(content, fname, is_private=0):
	"""write file to disk with a random name (to compare)"""
	file_path = get_files_path(is_private=is_private)

	# create directory (if not exists)
	frappe.create_folder(file_path)
	# write the file
	with open(os.path.join(file_path.encode('utf-8'), fname.encode('utf-8')), 'w+') as f:
		f.write(content)

	return get_files_path(fname, is_private=is_private)
Example #33
0
def get_email_other_path(data, file_name, reqId, sender):

    path_join = os.path.join
    rdoc = frappe.get_doc(data.get("doctype"), data.get('report_name'))
    for_all_sites = rdoc.jasper_all_sites_report
    jasper_path = get_jasper_path(for_all_sites)
    jasper_path_intern = path_join("jasper_sent_email", sender, reqId)
    outputPath = path_join(jasper_path, jasper_path_intern)
    frappe.create_folder(outputPath)
    file_path = path_join(outputPath, file_name)

    return file_path
def get_email_other_path(data, file_name, reqId, sender):

	path_join = os.path.join
	rdoc = frappe.get_doc(data.get("doctype"), data.get('report_name'))
	for_all_sites = rdoc.jasper_all_sites_report
	jasper_path = get_jasper_path(for_all_sites)
	jasper_path_intern = path_join("jasper_sent_email", sender, reqId)
	outputPath = path_join(jasper_path, jasper_path_intern)
	frappe.create_folder(outputPath)
	file_path = path_join(outputPath, file_name)

	return file_path
Example #35
0
def get_js_to_client():
    fluorine_temp_path = os.path.join(frappe.get_app_path("fluorine"),
                                      "templates", "react", "temp")
    frappe.create_folder(fluorine_temp_path)
    copy_client_files(fluorine_temp_path)
    files_in_lib, files_to_read, main_files = read_client_files(
        fluorine_temp_path)
    hooks_js = move_to_public(files_in_lib, files_to_read, main_files)

    remove_directory(fluorine_temp_path)

    return hooks_js
Example #36
0
def write_file(content, fname, is_private=0):
	"""write file to disk with a random name (to compare)"""
	file_path = get_files_path(is_private=is_private)

	# create directory (if not exists)
	frappe.create_folder(file_path)
	# write the file
	if isinstance(content, text_type):
		content = content.encode()
	with open(os.path.join(file_path.encode('utf-8'), fname.encode('utf-8')), 'wb+') as f:
		f.write(content)

	return get_files_path(fname, is_private=is_private)
Example #37
0
def make_site_config(db_name=None, db_password=None, site_config=None):
    db_name = db_name[:16]
    if "." in db_name:
        dn = db_name.split('.')
        db_name = dn[0]
    frappe.create_folder(os.path.join(frappe.local.site_path))
    site_file = os.path.join(frappe.local.site_path, "site_config.json")

    if not os.path.exists(site_file):
        if not (site_config and isinstance(site_config, dict)):
            site_config = get_conf_params(db_name, db_password)

        with open(site_file, "w") as f:
            f.write(json.dumps(site_config, indent=1, sort_keys=True))
Example #38
0
def make_site_config(db_name=None, db_password=None, site_config=None):
	db_name=db_name[:16]
	if "." in db_name: 
		dn=db_name.split('.')
		db_name=dn[0]
	frappe.create_folder(os.path.join(frappe.local.site_path))
	site_file = os.path.join(frappe.local.site_path, "site_config.json")

	if not os.path.exists(site_file):
		if not (site_config and isinstance(site_config, dict)):
			site_config = get_conf_params(db_name, db_password)

		with open(site_file, "w") as f:
			f.write(json.dumps(site_config, indent=1, sort_keys=True))
Example #39
0
def write_file(content, fname, is_private=0):
    """write file to disk with a random name (to compare)"""
    file_path = get_files_path(is_private=is_private)

    # create directory (if not exists)
    frappe.create_folder(file_path)
    # write the file
    if isinstance(content, text_type):
        content = content.encode()
    with open(os.path.join(file_path.encode("utf-8"), fname.encode("utf-8")),
              "wb+") as f:
        f.write(content)

    return get_files_path(fname, is_private=is_private)
Example #40
0
	def write_file(self):
		"""write file to disk with a random name (to compare)"""
		file_path = get_files_path(is_private=self.is_private)

		# create directory (if not exists)
		frappe.create_folder(file_path)
		# write the file
		self.content = self.get_content()
		if isinstance(self.content, text_type):
			self.content = self.content.encode()
		with open(os.path.join(file_path.encode('utf-8'), self.file_name.encode('utf-8')), 'wb+') as f:
			f.write(self.content)

		return get_files_path(self.file_name, is_private=self.is_private)
Example #41
0
    def on_update(self, method=None):

        paths = ["/assets/fluorine/js/before_fluorine_helper.js", "/assets/fluorine/js/meteor.devel.js" if fluor.check_dev_mode() else "/assets/js/meteor.js",\
          "/assets/fluorine/js/after_fluorine_helper.js"]
        #print "self.fluorine_reactivity {}".format(self.fluorine_reactivity)
        if self.fluorine_state == "off":
            return

        objjs = reactivity(react.get(self.fluorine_reactivity, None), paths)

        if not objjs:
            return

        hooks = frappe.get_hooks(app_name="fluorine")
        hooks.pop("base_template", None)
        hooks.pop("home_page", None)
        #remove_react_from_hook(hooks, paths)

        #if hooks.app_include_js:
        #	hooks.app_include_js.extend(objjs.get("app_include_js"))
        #else:
        hooks.update(objjs)

        if self.fluorine_base_template and self.fluorine_base_template.lower(
        ) != "default" and self.fluorine_state == "on":
            #fluor.set_base_template(self.fluorine_base_template)
            #objjs["base_template"] = [self.fluorine_base_template]
            hooks["base_template"] = [
                self.fluorine_base_template
            ]  #frappe.get_app_path("fluorine") + "/templates" + "/fluorine_base.html"
            hooks["home_page"] = "fluorine_home"

        fluorine_publicjs_path = os.path.join(frappe.get_app_path("fluorine"),
                                              "public", "js", "react")
        frappe.create_folder(fluorine_publicjs_path)

        fluor.save_batch_hook(hooks,
                              frappe.get_app_path("fluorine") + "/hooks.py")

        fluor.clear_frappe_caches()

        #elif self.fluorine_base_template.lower() == "default" or self.fluorine_state == "off":
        #	fluor.remove_base_template()
        #fluor.save_batch_hook_all("hooks_helper", objjs)
        #if not in dev mode compile to meteor.js
        if not fluor.check_dev_mode():
            #file.observer.stop()
            #jq = 1 if self.fluorine_base_template and self.fluorine_base_template.lower() != "default" else 0
            jq = 0
            file.make_meteor_file(jquery=jq, devmode=0)
Example #42
0
def create_folder(module, dt, dn, create_init):
    module_path = get_module_path(module)

    dt, dn = scrub_dt_dn(dt, dn)

    # create folder
    folder = os.path.join(module_path, dt, dn)

    frappe.create_folder(folder)

    # create init_py_files
    if create_init:
        create_init_py(module_path, dt, dn)

    return folder
Example #43
0
def create_folder(module, dt, dn, create_init):
	module_path = get_module_path(module)

	dt, dn = scrub_dt_dn(dt, dn)

	# create folder
	folder = os.path.join(module_path, dt, dn)

	frappe.create_folder(folder)

	# create init_py_files
	if create_init:
		create_init_py(module_path, dt, dn)

	return folder
Example #44
0
def setProfileImage():
	import os
	from frappe.utils import  get_files_path
	data = json.loads(frappe.local.request.data)

	if data.get('file_name'):
		file_path = "%(files_path)s/%(profile_id)s/%(file_name)s"%{'files_path': get_files_path(), "profile_id": data.get('profile_id'),
			'file_name': data.get('file_name')
		}
		path = os.path.join(os.getcwd(), get_files_path()[2:], data.get('profile_id'))
		frappe.create_folder(path)
		with open("%s/%s"%(path,data.get('file_name')), 'wb') as f:
	 		f.write(base64.b64decode(data.get('bin_img')))

 	res = update_profile_image(data.get('profile_id'), data.get('file_name'))
 	return {"filestatus": res}
Example #45
0
def write_translations_file(app, lang, app_messages=None):
    """Write a translation file for a given language.

	:param app: `app` for which translations are to be written.
	:param lang: Language code.
	:param app_messages: Source strings (optional).
	"""
    if not app_messages:
        app_messages = get_messages_for_app(app)

    if not app_messages:
        return

    tpath = frappe.get_pymodule_path(app, "translations")
    frappe.create_folder(tpath)
    write_json_file(os.path.join(tpath, lang + ".json"), app_messages)
Example #46
0
def get_file_name(doctype, state=""):
    """
	Returns the filename and path for logging purposes given the doctype
	:param doctype: DocType involved
	"""

    today = frappe.utils.nowdate()
    pathname = "logs/{0}".format(scrub(doctype))

    frappe.create_folder(pathname)

    return "{pathname}/{doctype}_sync_{state}{date}.log".format(
        date=scrub(today),
        pathname=pathname,
        state=state,
        doctype=scrub(doctype))
def attach_file_to_doc(filedata, doc_type, doc_name, file_name):
    if filedata:
        file_path = get_files_path(is_private=0)
        folder = doc_name + "-" + random_string(7)
        frappe.create_folder(file_path + "/" + folder)
        #folder = get_files_path(folder, is_private = 1) #"/private/files/" + folder + "/"
        fd_json = json.loads(filedata)
        fd_list = list(fd_json["files_data"])
        for fd in fd_list:
            content_type = mimetypes.guess_type(fd["filename"])[0]
            filedoc = save_file_on_filesystem(fd["filename"],
                                              fd["dataurl"],
                                              folder=folder,
                                              content_type=content_type,
                                              is_private=0)
        #frappe.msgprint(filedoc)
    return filedoc
Example #48
0
def write_translations_file(app, lang, full_dict=None, app_messages=None):
	"""Write a translation file for a given language.
	:param app: `app` for which translations are to be written.
	:param lang: Language code.
	:param full_dict: Full translated language dict (optional).
	:param app_messages: Source strings (optional).
	"""
	if not app_messages:
		app_messages = get_messages_for_app(app)

	if not app_messages:
		return

	tpath = frappe.get_pymodule_path(app, "translations")
	frappe.create_folder(tpath)
	write_csv_file(os.path.join(tpath, lang + ".csv"),
		app_messages, full_dict or get_full_dict(lang))
Example #49
0
def copy_files_to_visit(dms_file_list, visit_id):
    import os, shutil, glob
    for loc in dms_file_list:
        print "--------------------------file loc -------------------"
        print loc.get('file_location')

        path_lst = loc.get('file_location')[0].split('/')

        file_path = os.path.join('/'.join(path_lst[0:len(path_lst) - 1]),
                                 visit_id)

        frappe.create_folder(file_path)

        for filename in glob.glob(
                os.path.join('/'.join(path_lst[0:len(path_lst) - 1]), '*.*')):
            print filename
            shutil.move(filename, file_path)
Example #50
0
def write_chart_to_file(account_tree, company):
	"""
		Write chart to json file and make tar file for all charts
	"""
	chart = {}
	chart["name"] = company.name
	chart["country_code"] = frappe.db.get_value("Country", company.country, "code")
	chart["tree"] = account_tree
	
	path = os.path.join(os.path.abspath(frappe.get_site_path()), "public", "files", "submitted_charts")
	frappe.create_folder(path)
	
	fpath = os.path.join(path, company.name + ".json")
	if not os.path.exists(fpath):
		with open(os.path.join(path, company.name + ".json"), "w") as f:
			f.write(json.dumps(chart, indent=4, sort_keys=True))
			
	with tarfile.open(os.path.join(path, "charts.tar.gz"), "w:gz") as tar:
		tar.add(path)
Example #51
0
def get_images_path(compiled_path):
	images_path = frappe.utils.get_path("images", base=compiled_path)
	frappe.create_folder(images_path)
	return images_path
def execute():
	if not os.path.exists(os.path.join(frappe.local.site_path, 'private', 'files')):
		frappe.create_folder(os.path.join(frappe.local.site_path, 'private', 'files'))
	def _run_report_async(self, path, doc, data=None, params=None, pformat="pdf", ncopies=1, for_all_sites=0):

		data = data or {}
		hashmap = jr.HashMap()
		pram, pram_server, copies = self.do_params(data, params, pformat, doc)
		pram_copy_index = copies.get("pram_copy_index", -1)
		pram_copy_page_index = copies.get("pram_copy_page_index", -1)

		path_join = os.path.join
		resp = []
		custom = doc.get("jasper_custom_fields")

		pram.extend(self.get_param_hook(doc, data, pram_server))

		self.populate_hashmap(pram, hashmap, doc.jasper_report_name)

		copies = [_("Original"), _("Duplicate"), _("Triplicate")]
		conn = ""
		if doc.query:
			conn = "jdbc:mysql://" + (frappe.conf.db_host or '127.0.0.1') + ":" + (frappe.conf.db_port or "3306") + "/" + frappe.conf.db_name + "?user="******"&password="******"report_name"))
			batch.outtype = print_format.index(pformat)
			batch.batchReport.setType(batch.outtype)
			batch.batchReport.setFileName(batch.reportName)
			reqId = uuid.uuid4().hex
			batch.outputPath = path_join(batch.compiled_path, reqId)
			frappe.create_folder(batch.outputPath)
			batch.batchReport.setOutputPath(batch.outputPath + os.sep + batch.reportName)
			batch.sessionId = "local_report_" + reqId

			res = self.prepareResponse({"reportURI": os.path.relpath(batch.outputPath, batch.jasper_path) + os.sep + batch.reportName + "." + pformat}, batch.sessionId)
			res["status"] = None
			res["report_name"] = data.get("report_name")
			resp.append(res)

			batch.batchReport.setTaskHandler(self.frappe_task)
			result = {"fileName": batch.reportName + "." + pformat, "uri":batch.outputPath + os.sep + batch.reportName + "." + pformat, "last_updated": res.get("reqtime"), 'session_expiry': utils.get_expiry_period(batch.sessionId)}
			self.insert_jasper_reqid_record(batch.sessionId, {"data":{"result":result, "report_name": data.get("report_name"), "last_updated": frappe.utils.now(),'session_expiry': utils.get_expiry_period()}})

			frappe.local.batch = batch

		lang = data.get("params", {}).get("locale", None) or "EN"
		cur_doctype = data.get("cur_doctype")
		ids = data.get('ids', [])[:]
		virtua = 0
		if doc.jasper_virtualizer:
			virtua = cint(frappe.db.get_value('JasperServerConfig', fieldname="jasper_virtualizer_pages")) or 0

		if custom and not frappe.local.fds:
			default = ['jasper_erpnext_report.jasper_reports.FrappeDataSource.JasperCustomDataSourceDefault']
			jds_method = utils.jasper_run_method_once_with_default("jasper_custom_data_source", data.get("report_name"), default)
			frappe.local.fds = jds_method

		for m in range(ncopies):
			if pram_copy_index != -1:
				values = pram[pram_copy_index].get("value","")
				pram_copy_name = pram[pram_copy_index].get("name","")
				if not values or not values[0]:
					hashmap.put(pram_copy_name, copies[m])
				else:
					hashmap.put(pram_copy_name, frappe.utils.strip(values[m], ' \t\n\r'))
			if pram_copy_page_index != -1:
				pram_copy_page_name = pram[pram_copy_page_index].get("name","")
				hashmap.put(pram_copy_page_name, str(m) + _(" of ") + str(ncopies))

			mparams = jr.HashMap()
			mparams.put("path_jasper_file", frappe.local.batch.compiled_path + os.sep)
			mparams.put("reportName", frappe.local.batch.reportName)
			mparams.put("outputPath", frappe.local.batch.outputPath + os.sep)
			mparams.put("params", hashmap)
			mparams.put("conn", conn)
			mparams.put("type", jr.Integer(frappe.local.batch.outtype))
			mparams.put("lang", lang)
			mparams.put("virtua", jr.Integer(virtua))
			#used for xml datasource
			mparams.put("numberPattern", frappe.db.get_default("number_format"))
			mparams.put("datePattern", frappe.db.get_default("date_format") + " HH:mm:ss")

			self._export_report(mparams, data.get("report_name"), data.get("grid_data"), frappe.local.batch.sessionId, cur_doctype, custom, ids, frappe.local.fds)
			if pram_copy_index != -1 and ncopies > 1:
				hashmap = jr.HashMap()
				self.populate_hashmap(pram, hashmap, doc.jasper_report_name)

		return resp
def get_compiled_path(dir_path, dn):
	jrxml_path = get_jrxml_path(dir_path, dn)
	compiled_path = frappe.utils.get_path("compiled", base=jrxml_path)
	frappe.create_folder(compiled_path)
	return compiled_path
Example #55
0
def get_html_reports_images_path(report_path, where="images"):
	path = os.path.join(report_path, where)
	frappe.create_folder(path)
	return path
def make_jasper_hooks_path():
	jasper_hooks_path = frappe.get_site_path("jasper_hooks_" + frappe.local.site.replace(".", "_"))
	frappe.create_folder(jasper_hooks_path, with_init=True)
	return jasper_hooks_path
Example #57
0
def make_boilerplate(dest):
	if not os.path.exists(dest):
		print "Destination directory does not exist"
		return

	hooks = frappe._dict()
	for key in ("App Name", "App Title", "App Description", "App Publisher",
		"App Icon", "App Color", "App Email", "App URL", "App License"):
		hook_key = key.lower().replace(" ", "_")
		hook_val = None
		while not hook_val:
			hook_val = raw_input(key + ": ")
			if hook_key=="app_name" and hook_val.lower().replace(" ", "_") != hook_val:
				print "App Name must be all lowercase and without spaces"
				hook_val = ""

		hooks[hook_key] = hook_val

	frappe.create_folder(os.path.join(dest, hooks.app_name, hooks.app_name, hooks.app_name))
	frappe.create_folder(os.path.join(dest, hooks.app_name, hooks.app_name, "templates"))
	frappe.create_folder(os.path.join(dest, hooks.app_name, hooks.app_name, "templates",
		"statics"))
	frappe.create_folder(os.path.join(dest, hooks.app_name, hooks.app_name, "templates",
		"pages"))
	frappe.create_folder(os.path.join(dest, hooks.app_name, hooks.app_name, "templates",
		"generators"))
	frappe.create_folder(os.path.join(dest, hooks.app_name, hooks.app_name, "config"))

	# init files
	touch_file(os.path.join(dest, hooks.app_name, hooks.app_name, "__init__.py"))
	touch_file(os.path.join(dest, hooks.app_name, hooks.app_name, hooks.app_name, "__init__.py"))
	touch_file(os.path.join(dest, hooks.app_name, hooks.app_name, "templates", "__init__.py"))
	touch_file(os.path.join(dest, hooks.app_name, hooks.app_name, "templates",
		"pages", "__init__.py"))
	touch_file(os.path.join(dest, hooks.app_name, hooks.app_name, "templates",
		"generators", "__init__.py"))
	touch_file(os.path.join(dest, hooks.app_name, hooks.app_name, "config", "__init__.py"))

	with open(os.path.join(dest, hooks.app_name, "MANIFEST.in"), "w") as f:
		f.write(manifest_template.format(**hooks))

	with open(os.path.join(dest, hooks.app_name, ".gitignore"), "w") as f:
		f.write(gitignore_template)

	with open(os.path.join(dest, hooks.app_name, "setup.py"), "w") as f:
		f.write(setup_template.format(**hooks))

	with open(os.path.join(dest, hooks.app_name, "requirements.txt"), "w") as f:
		f.write("frappe")

	touch_file(os.path.join(dest, hooks.app_name, "README.md"))

	with open(os.path.join(dest, hooks.app_name, "license.txt"), "w") as f:
		f.write("License: " + hooks.app_license)

	with open(os.path.join(dest, hooks.app_name, hooks.app_name, "modules.txt"), "w") as f:
		f.write(hooks.app_name)

	with open(os.path.join(dest, hooks.app_name, hooks.app_name, "hooks.py"), "w") as f:
		f.write(hooks_template.format(**hooks))

	touch_file(os.path.join(dest, hooks.app_name, hooks.app_name, "patches.txt"))

	with open(os.path.join(dest, hooks.app_name, hooks.app_name, "config", "desktop.py"), "w") as f:
		f.write(desktop_template.format(**hooks))
Example #58
0
def get_html_reports_path(report_name, where="reports", hash=None, localsite=None):
	site = localsite or frappe.local.site
	path_jasper_module = os.path.dirname(jasper_erpnext_report.__file__)
	path = os.path.join(path_jasper_module, "public", where, site, report_name, hash)
	frappe.create_folder(path)
	return path
def make_boilerplate(dest, app_name):
	if not os.path.exists(dest):
		print "Destination directory does not exist"
		return

	hooks = frappe._dict()
	hooks.app_name = app_name
	app_title = hooks.app_name.replace("_", " ").title()
	for key in ("App Title (defaut: {0})".format(app_title),
		"App Description", "App Publisher", "App Email",
		"App Icon (default 'octicon octicon-file-directory')",
		"App Color (default 'grey')",
		"App License (default 'MIT')"):
		hook_key = key.split(" (")[0].lower().replace(" ", "_")
		hook_val = None
		while not hook_val:
			hook_val = cstr(raw_input(key + ": "))
			if hook_key=="app_name" and hook_val.lower().replace(" ", "_") != hook_val:
				print "App Name must be all lowercase and without spaces"
				hook_val = ""
			elif not hook_val:
				defaults = {
					"app_title": app_title,
					"app_icon": "octicon octicon-file-directory",
					"app_color": "grey",
					"app_license": "MIT"
				}
				if hook_key in defaults:
					hook_val = defaults[hook_key]

		hooks[hook_key] = hook_val

	frappe.create_folder(os.path.join(dest, hooks.app_name, hooks.app_name, frappe.scrub(hooks.app_title)),
		with_init=True)
	frappe.create_folder(os.path.join(dest, hooks.app_name, hooks.app_name, "templates"), with_init=True)
	frappe.create_folder(os.path.join(dest, hooks.app_name, hooks.app_name, "www"))
	frappe.create_folder(os.path.join(dest, hooks.app_name, hooks.app_name, "templates",
		"pages"), with_init=True)
	frappe.create_folder(os.path.join(dest, hooks.app_name, hooks.app_name, "templates",
		"generators"), with_init=True)
	frappe.create_folder(os.path.join(dest, hooks.app_name, hooks.app_name, "templates",
		"includes"))
	frappe.create_folder(os.path.join(dest, hooks.app_name, hooks.app_name, "config"), with_init=True)

	touch_file(os.path.join(dest, hooks.app_name, hooks.app_name, "__init__.py"))

	with open(os.path.join(dest, hooks.app_name, "MANIFEST.in"), "w") as f:
		f.write(encode(manifest_template.format(**hooks)))

	with open(os.path.join(dest, hooks.app_name, ".gitignore"), "w") as f:
		f.write(encode(gitignore_template))

	with open(os.path.join(dest, hooks.app_name, "setup.py"), "w") as f:
		f.write(encode(setup_template.format(**hooks)))

	with open(os.path.join(dest, hooks.app_name, "requirements.txt"), "w") as f:
		f.write("frappe")

	with open(os.path.join(dest, hooks.app_name, "README.md"), "w") as f:
		f.write(encode("## {0}\n\n{1}\n\n#### License\n\n{2}".format(hooks.app_title,
			hooks.app_description, hooks.app_license)))

	with open(os.path.join(dest, hooks.app_name, "license.txt"), "w") as f:
		f.write(encode("License: " + hooks.app_license))

	with open(os.path.join(dest, hooks.app_name, hooks.app_name, "modules.txt"), "w") as f:
		f.write(encode(hooks.app_title))

	with open(os.path.join(dest, hooks.app_name, hooks.app_name, "hooks.py"), "w") as f:
		f.write(encode(hooks_template.format(**hooks)))

	touch_file(os.path.join(dest, hooks.app_name, hooks.app_name, "patches.txt"))

	with open(os.path.join(dest, hooks.app_name, hooks.app_name, "config", "desktop.py"), "w") as f:
		f.write(encode(desktop_template.format(**hooks)))

	print "'{app}' created at {path}".format(app=app_name, path=os.path.join(dest, app_name))