def execute():
	frappe.reload_doc("email", "doctype", "email_template")

	if not frappe.db.exists("Email Template", _('Leave Approval Notification')):
		base_path = frappe.get_app_path("erpnext", "hr", "doctype")
		response = frappe.read_file(os.path.join(base_path, "leave_application/leave_application_email_template.html"))
		frappe.get_doc({
			'doctype': 'Email Template',
			'name': _("Leave Approval Notification"),
			'response': response,
			'subject': _("Leave Approval Notification"),
			'owner': frappe.session.user,
		}).insert(ignore_permissions=True)


	if not frappe.db.exists("Email Template", _('Leave Status Notification')):
		base_path = frappe.get_app_path("erpnext", "hr", "doctype")
		response = frappe.read_file(os.path.join(base_path, "leave_application/leave_application_email_template.html"))
		frappe.get_doc({
			'doctype': 'Email Template',
			'name': _("Leave Status Notification"),
			'response': response,
			'subject': _("Leave Status Notification"),
			'owner': frappe.session.user,
		}).insert(ignore_permissions=True)
Example #2
0
def add_uom_data():
	# add UOMs
	uoms = json.loads(open(frappe.get_app_path("erpnext", "setup", "setup_wizard", "data", "uom_data.json")).read())
	for d in uoms:
		if not frappe.db.exists('UOM', _(d.get("uom_name"))):
			uom_doc = frappe.get_doc({
				"doctype": "UOM",
				"uom_name": _(d.get("uom_name")),
				"name": _(d.get("uom_name")),
				"must_be_whole_number": d.get("must_be_whole_number")
			}).insert(ignore_permissions=True)

	# bootstrap uom conversion factors
	uom_conversions = json.loads(open(frappe.get_app_path("erpnext", "setup", "setup_wizard", "data", "uom_conversion_data.json")).read())
	for d in uom_conversions:
		if not frappe.db.exists("UOM Category", _(d.get("category"))):
			frappe.get_doc({
				"doctype": "UOM Category",
				"category_name": _(d.get("category"))
			}).insert(ignore_permissions=True)

		uom_conversion = frappe.get_doc({
			"doctype": "UOM Conversion Factor",
			"category": _(d.get("category")),
			"from_uom": _(d.get("from_uom")),
			"to_uom": _(d.get("to_uom")),
			"value": d.get("value")
		}).insert(ignore_permissions=True)
Example #3
0
	def build_user_docs(self):
		"""Build templates for user docs pages, if missing."""
		#user_docs_path = os.path.join(self.docs_path, "user")

		# license
		with open(os.path.join(self.app_path, "..", "license.txt"), "r") as license_file:
			self.app_context["license_text"] = markdown(license_file.read())
			html = frappe.render_template("templates/autodoc/license.html",
				context = self.app_context)

		with open(os.path.join(self.docs_path, "license.html"), "w") as license_file:
			license_file.write(html.encode("utf-8"))

		# contents
		shutil.copy(os.path.join(frappe.get_app_path("frappe", "templates", "autodoc",
			"contents.html")), os.path.join(self.docs_path, "contents.html"))

		shutil.copy(os.path.join(frappe.get_app_path("frappe", "templates", "autodoc",
			"contents.py")), os.path.join(self.docs_path, "contents.py"))

		# install
		html = frappe.render_template("templates/autodoc/install.md",
			context = self.app_context)

		with open(os.path.join(self.docs_path, "install.md"), "w") as f:
			f.write(html)

		self.update_index_txt(self.docs_path)
Example #4
0
	def copy_assets(self):
		"""Copy jquery, bootstrap and other assets to files"""

		print "Copying assets..."
		assets_path = os.path.join(self.target, "assets")

		# copy assets from docs
		source_assets = frappe.get_app_path(self.app, "docs", "assets")
		if os.path.exists(source_assets):
			for basepath, folders, files in os.walk(source_assets):
				target_basepath = os.path.join(assets_path, os.path.relpath(basepath, source_assets))

				# make the base folder
				if not os.path.exists(target_basepath):
					os.makedirs(target_basepath)

				# copy all files in the current folder
				for f in files:
					shutil.copy(os.path.join(basepath, f), os.path.join(target_basepath, f))

		# make missing folders
		for fname in ("js", "css", "img"):
			path = os.path.join(assets_path, fname)
			if not os.path.exists(path):
				os.makedirs(path)

		copy_files = {
			"js/lib/jquery/jquery.min.js": "js/jquery.min.js",
			"js/lib/bootstrap.min.js": "js/bootstrap.min.js",
			"js/lib/highlight.pack.js": "js/highlight.pack.js",
			"css/bootstrap.css": "css/bootstrap.css",
			"css/font-awesome.css": "css/font-awesome.css",
			"css/docs.css": "css/docs.css",
			"css/hljs.css": "css/hljs.css",
			"css/font": "css/font",
			"css/octicons": "css/octicons",
			# always overwrite octicons.css to fix the path
			"css/octicons/octicons.css": "css/octicons/octicons.css",
			"images/frappe-bird-grey.svg": "img/frappe-bird-grey.svg"
		}

		for source, target in copy_files.iteritems():
			source_path = frappe.get_app_path("frappe", "public", source)
			if os.path.isdir(source_path):
				if not os.path.exists(os.path.join(assets_path, target)):
					shutil.copytree(source_path, os.path.join(assets_path, target))
			else:
				shutil.copy(source_path, os.path.join(assets_path, target))

		# fix path for font-files
		files = (
			os.path.join(assets_path, "css", "octicons", "octicons.css"),
			os.path.join(assets_path, "css", "font-awesome.css"),
		)

		for path in files:
			with open(path, "r") as css_file:
				text = css_file.read()
			with open(path, "w") as css_file:
				css_file.write(text.replace("/assets/frappe/", self.docs_base_url + '/assets/'))
Example #5
0
	def __init__(self, app, docs_app, path):
		"""Generate source templates for models reference and module API.

		Must set globals `self.models_base_path`, `self.api_base_path` and `self.app_path`.
		"""
		self.app = app
		self.app_path = frappe.get_app_path(app)
		if path[0]=="/": path = path[1:]
		path = frappe.get_app_path(docs_app, path)
		self.models_base_path = os.path.join(path, "models")
		self.api_base_path = os.path.join(path, "api")

		for basepath, folders, files in os.walk(self.app_path):
			if "doctype" not in basepath:
				if "doctype" in folders:
					module = os.path.basename(basepath)

					module_folder = os.path.join(self.models_base_path, module)

					self.make_folder(module_folder)
					self.update_index_txt(module_folder)

			if "doctype" in basepath:
				parts = basepath.split("/")
				#print parts
				module, doctype = parts[-3], parts[-1]

				if doctype not in ("doctype", "boilerplate"):
					self.write_model_file(basepath, module, doctype)

			elif self.is_py_module(basepath, folders, files):
				self.write_modules(basepath, folders, files)
Example #6
0
def export_fixture(doctype, app):
	if frappe.session.user != "Administrator":
		raise frappe.PermissionError

	if not os.path.exists(frappe.get_app_path(app, "fixtures")):
		os.mkdir(frappe.get_app_path(app, "fixtures"))

	export_json(doctype, frappe.get_app_path(app, "fixtures", frappe.scrub(doctype) + ".json"))
Example #7
0
def add_web_forms():
	"""Import web forms for Issues and Addresses"""
	from frappe.modules.import_file import import_file_by_path

	import_file_by_path(frappe.get_app_path("erpnext", "setup/fixtures/web_form/issues.json"),
		data_import=True)
	import_file_by_path(frappe.get_app_path("erpnext", "setup/fixtures/web_form/addresses.json"),
		data_import=True)
Example #8
0
def export_fixtures():
	"""Export fixtures as JSON to `[app]/fixtures`"""
	for app in frappe.get_installed_apps():
		for fixture in frappe.get_hooks("fixtures", app_name=app):
			print "Exporting {0}".format(fixture)
			if not os.path.exists(frappe.get_app_path(app, "fixtures")):
				os.mkdir(frappe.get_app_path(app, "fixtures"))

			export_json(fixture, frappe.get_app_path(app, "fixtures", frappe.scrub(fixture) + ".json"))
Example #9
0
def list_old_images():
	import os, frappe

	for basepath, folders, files in os.walk(frappe.get_app_path("manual_erpnext_com", "www")):
		for fname in files:
			with open(os.path.join(basepath, fname), "r") as f:
				content = f.read()
				if "old_images" in content:
					print os.path.relpath(os.path.join(basepath, fname), frappe.get_app_path("manual_erpnext_com"))
Example #10
0
def export_fixtures():
	for app in frappe.get_installed_apps():
		for fixture in frappe.get_hooks("fixtures", app_name=app):
			print "Exporting " + fixture
			if not os.path.exists(frappe.get_app_path(app, "fixtures")):
				os.mkdir(frappe.get_app_path(app, "fixtures"))
			if frappe.db.get_value("DocType", fixture, "issingle"):
				export_fixture(fixture, fixture, app)
			else:
				export_csv(fixture, frappe.get_app_path(app, "fixtures", frappe.scrub(fixture) + ".csv"))
Example #11
0
			def trigger_make(source_path, event_type):
				if "/docs/user/" in source_path:
					# user file
					target_path = frappe.get_app_path(target, 'www', 'docs', 'user',
						os.path.relpath(source_path, start=frappe.get_app_path(app, 'docs', 'user')))
					shutil.copy(source_path, target_path)
					add_breadcrumbs_tag(target_path)

				if source_path.endswith('/docs/index.md'):
					target_path = frappe.get_app_path(target, 'www', 'docs', 'index.md')
					shutil.copy(source_path, target_path)
Example #12
0
def sync_fixtures(app=None):
	if app:
		apps = [app]
	else:
		apps = frappe.get_installed_apps()
	for app in apps:
		if os.path.exists(frappe.get_app_path(app, "fixtures")):
			for fname in os.listdir(frappe.get_app_path(app, "fixtures")):
				if fname.endswith(".json") or fname.endswith(".csv"):
					import_doc(frappe.get_app_path(app, "fixtures", fname), ignore_links=True, overwrite=True)

	frappe.db.commit()
Example #13
0
def export_fixtures():
	for app in frappe.get_installed_apps():
		for fixture in frappe.get_hooks("fixtures", app_name=app):
			print "Exporting {0}".format(fixture)
			if not os.path.exists(frappe.get_app_path(app, "fixtures")):
				os.mkdir(frappe.get_app_path(app, "fixtures"))
			if isinstance(fixture, basestring):
				fixture = [fixture];
			if frappe.db.get_value("DocType", fixture[0], "issingle"):
				export_fixture(fixture[0], fixture[0], app)
			else:
				export_csv(fixture, frappe.get_app_path(app, "fixtures", frappe.scrub(fixture[0]) + ".csv"))
Example #14
0
def export_fixtures():
	"""Export fixtures as JSON to `[app]/fixtures`"""
	for app in frappe.get_installed_apps():
		for fixture in frappe.get_hooks("fixtures", app_name=app):
			filters = None
			if isinstance(fixture, dict):
				filters = fixture.get("filters")
				fixture = fixture.get("doctype") or fixture.get("dt")
			print "Exporting {0} app {1} filters {2}".format(fixture, app, filters)
			if not os.path.exists(frappe.get_app_path(app, "fixtures")):
				os.mkdir(frappe.get_app_path(app, "fixtures"))

			export_json(fixture, frappe.get_app_path(app, "fixtures", frappe.scrub(fixture) + ".json"), filters=filters)
Example #15
0
def get_tests_for(app=None, test_list=None):
	tests = []
	if test_list:
		# Get all tests from a particular txt file
		app, test_list = test_list.split(os.path.sep, 1)
		tests_path = frappe.get_app_path(app, test_list)
	else:
		# Get all tests for a particular app
		tests_path = frappe.get_app_path(app, 'tests', 'ui', 'tests.txt')
	if os.path.exists(tests_path):
		with open(tests_path, 'r') as fileobj:
			tests = fileobj.read().strip().splitlines()
	return tests
Example #16
0
def get_all_messages_from_js_files(app_name=None):
	"""Extracts all translatable strings from app `.js` files"""
	messages = []
	for app in ([app_name] if app_name else frappe.get_installed_apps()):
		if os.path.exists(frappe.get_app_path(app, "public")):
			for basepath, folders, files in os.walk(frappe.get_app_path(app, "public")):
				if "frappe/public/js/lib" in basepath:
					continue

				for fname in files:
					if fname.endswith(".js") or fname.endswith(".html"):
						messages.extend(get_messages_from_file(os.path.join(basepath, fname)))

	return messages
Example #17
0
	def copy_user_assets(self):
		'''Copy docs/user and docs/assets to the target app'''
		print('Copying docs/user and docs/assets...')
		shutil.rmtree(os.path.join(self.docs_path, 'user'),
			ignore_errors=True)
		shutil.rmtree(os.path.join(self.docs_path, 'assets'),
			ignore_errors=True)
		shutil.copytree(os.path.join(self.app_path, 'docs', 'user'),
			os.path.join(self.docs_path, 'user'))
		shutil.copytree(os.path.join(self.app_path, 'docs', 'assets'),
			frappe.get_app_path(self.target_app, 'www', 'docs', 'assets'))

		# copy index
		shutil.copy(os.path.join(self.app_path, 'docs', 'index.md'),
			frappe.get_app_path(self.target_app, 'www', 'docs'))
Example #18
0
def get_change_log_for_app(app, from_version, to_version):
	change_log_folder = os.path.join(frappe.get_app_path(app), "change_log")
	if not os.path.exists(change_log_folder):
		return

	from_version = Version(from_version)
	to_version = Version(to_version)
	# remove pre-release part
	to_version.prerelease = None

	major_version_folders = ["v{0}".format(i) for i in range(from_version.major, to_version.major + 1)]
	app_change_log = []

	for folder in os.listdir(change_log_folder):
		if folder in major_version_folders:
			for file in os.listdir(os.path.join(change_log_folder, folder)):
				version = Version(os.path.splitext(file)[0][1:].replace("_", "."))

				if from_version < version <= to_version:
					file_path = os.path.join(change_log_folder, folder, file)
					content = frappe.read_file(file_path)
					app_change_log.append([version, content])

	app_change_log = sorted(app_change_log, key=lambda d: d[0], reverse=True)

	# convert version to string and send
	return [[cstr(d[0]), d[1]] for d in app_change_log]
Example #19
0
	def create_api_version_folder(self):
		"""Creates a folder `[app]/versions/[version]` and adds `__init__.py`"""
		module_path = frappe.get_app_path(self.app_name, "versions",self.name)
		if not os.path.exists(module_path):
			os.mkdir(module_path)
			with open(os.path.join(module_path, "__init__.py"), "w") as f:
				f.write("")
Example #20
0
def sync_fixtures(app=None):
	"""Import, overwrite fixtures from `[app]/fixtures`"""
	if app:
		apps = [app]
	else:
		apps = frappe.get_installed_apps()
	for app in apps:
		if os.path.exists(frappe.get_app_path(app, "fixtures")):
			fixture_files = sorted(os.listdir(frappe.get_app_path(app, "fixtures")))
			for fname in fixture_files:
				if fname.endswith(".json") or fname.endswith(".csv"):
					import_doc(frappe.get_app_path(app, "fixtures", fname), ignore_links=True, overwrite=True)

		import_custom_scripts(app)

	frappe.db.commit()
Example #21
0
def update_language_names():
	'''Update frappe/geo/languages.json names (for use via patch)'''
	with open(frappe.get_app_path('frappe', 'geo', 'languages.json'), 'r') as f:
		data = json.loads(f.read())

	for l in data:
		frappe.db.set_value('Language', l['code'], 'language_name', l['name'])
Example #22
0
def get_pages():
	pages = frappe.cache().get_value("_website_pages")
	if not pages:
		pages = []
		for app in frappe.get_installed_apps():
			app_path = frappe.get_app_path(app)
			path = os.path.join(app_path, "templates", "pages")
			if os.path.exists(path):
				for fname in os.listdir(path):
					fname = frappe.utils.cstr(fname)
					page_name, extn = fname.rsplit(".", 1)
					if extn in ("html", "xml", "js", "css"):
						route_page_name = page_name if extn=="html" else fname

						# add website route
						route = frappe._dict()
						route.page_or_generator = "Page"
						route.template = os.path.relpath(os.path.join(path, fname), app_path)
						route.name = route.page_name = route_page_name
						route.public_read = 1
						controller_path = os.path.join(path, page_name + ".py")

						if os.path.exists(controller_path):
							controller = app + "." + os.path.relpath(controller_path,
								app_path).replace(os.path.sep, ".")[:-3]
							route.controller = controller
							try:
								route.page_title = frappe.get_attr(controller + "." + "page_title")
							except AttributeError:
								pass

						pages.append(route)

		frappe.cache().set_value("_website_pages", pages)
	return pages
Example #23
0
def setup_item():
	items = json.loads(open(frappe.get_app_path('erpnext', 'demo', 'data', 'item.json')).read())
	for i in items:
		item = frappe.new_doc('Item')
		item.update(i)
		item.default_warehouse = frappe.get_all('Warehouse', filters={'warehouse_name': item.default_warehouse}, limit=1)[0].name
		item.insert()
Example #24
0
def render_include(content):
	'''render {% include "app/path/filename" in js file %}'''

	content = cstr(content)

	# try 5 levels of includes
	for i in xrange(5):
		if "{% include" in content:
			paths = re.findall(r'''{% include\s['"](.*)['"]\s%}''', content)
			if not paths:
				frappe.throw('Invalid include path')

			for path in paths:
				app, app_path = path.split('/', 1)
				with open(frappe.get_app_path(app, app_path), 'r') as f:
					include = unicode(f.read(), 'utf-8')
					if path.endswith('.html'):
						include = html_to_js_template(path, include)

					content = re.sub(r'''{{% include\s['"]{0}['"]\s%}}'''.format(path), include, content)

		else:
			break

	return content
def execute():
	for page in frappe.db.sql("""select * from `tabWeb Page`""", as_dict=1):
		# get parents
		
		route = frappe.db.get_value("Website Route", {"ref_doctype":"Web Page", "docname": page.name},
			["name", "lft", "rgt"], as_dict=1)
			
		if route and page.parent_website_route:
			path = frappe.get_app_path("frappe_io", "templates", "statics", 
				*page.parent_website_route.split("/"))
				
			print path
			if not os.path.exists(path):
				os.makedirs(path)

			index_txt_path = os.path.join(path, "index.txt")
			if not os.path.exists(index_txt_path):
				with open(index_txt_path, "w") as f:
					f.write("\n".join(frappe.db.sql_list("""select name from `tabWeb Page` 
						where parent_website_route=%s order by idx""", page.parent_website_route)))

			index_md = os.path.join(path, "index.md")
			if not os.path.exists(index_md):
				with open(index_md, "w") as f:
					f.write("")
				
			page_name = route.name.split("/")[-1]
			with open(os.path.join(path, page_name + ".md"), "w") as mdfile:
				mdfile.write(html2text(page.main_section or "").encode("utf-8"))
Example #26
0
def sync_for(app_name, force=0, sync_everything = False, verbose=False):
	files = []

	if app_name == "frappe":
		# these need to go first at time of install
		for d in (("core", "docfield"), ("core", "docperm"), ("core", "doctype"),
			("core", "user"), ("core", "role"), ("custom", "custom_field"),
			("custom", "property_setter")):
			files.append(os.path.join(frappe.get_app_path("frappe"), d[0],
				"doctype", d[1], d[1] + ".json"))

	for module_name in frappe.local.app_modules.get(app_name) or []:
		folder = os.path.dirname(frappe.get_module(app_name + "." + module_name).__file__)
		get_doc_files(files, folder, force, sync_everything, verbose=verbose)

	l = len(files)
	if l:
		for i, doc_path in enumerate(files):
			import_file_by_path(doc_path, force=force)
			#print module_name + ' | ' + doctype + ' | ' + name

			frappe.db.commit()

			# show progress bar
			update_progress_bar("Updating {0}".format(app_name), i, l)

		print ""
Example #27
0
	def add_to_modules_txt(self):
		"""Adds to `[app]/modules.txt`"""
		modules = None
		if not frappe.local.module_app.get(frappe.scrub(self.name)):
			with open(frappe.get_app_path(self.app_name, "modules.txt"), "r") as f:
				content = f.read()
				if not self.name in content.splitlines():
					modules = list(filter(None, content.splitlines()))
					modules.append(self.name)

			if modules:
				with open(frappe.get_app_path(self.app_name, "modules.txt"), "w") as f:
					f.write("\n".join(modules))

				frappe.clear_cache()
				frappe.setup_module_map()
Example #28
0
def get_pages_and_generators(app):
    pages = []
    generators = []
    app_path = frappe.get_app_path(app)

    for config_type in ("pages", "generators"):
        path = os.path.join(app_path, "templates", config_type)
        if os.path.exists(path):
            for fname in os.listdir(path):
                fname = frappe.utils.cstr(fname)
                if fname.split(".")[-1] in ("html", "xml", "js", "css"):
                    if config_type == "pages":
                        pages.append(
                            {
                                "page_or_generator": "Page",
                                "app": app,
                                "path": path,
                                "fname": fname,
                                "app_path": app_path,
                            }
                        )
                    else:
                        generators.append(
                            {
                                "page_or_generator": "Generator",
                                "app": app,
                                "path": path,
                                "fname": fname,
                                "app_path": app_path,
                            }
                        )

    return pages, generators
Example #29
0
def purifycss():
	with open(source, 'r') as f:
		src = f.read()

	classes = []
	for line in src.splitlines():
		line = line.strip()
		if not line:
			continue
		if line[0]=='@':
			continue
		classes.extend(re.findall('\.([^0-9][^ :&.{,(]*)', line))

	classes = list(set(classes))

	for app in target_apps:
		for basepath, folders, files in os.walk(frappe.get_app_path(app)):
			for fname in files:
				if fname.endswith('.html') or fname.endswith('.md'):
					#print 'checking {0}...'.format(fname)
					with open(os.path.join(basepath, fname), 'r') as f:
						src = f.read()
					for c in classes:
						if c in src:
							classes.remove(c)

	for c in sorted(classes):
		print(c)
Example #30
0
def get_tests_for(app):
	'''Get all tests for a particular app'''
	tests = []
	tests_path = frappe.get_app_path(app, 'tests', 'ui', 'tests.txt')
	if os.path.exists(tests_path):
		with open(tests_path, 'r') as fileobj:
			tests = fileobj.read().strip().splitlines()
	return tests
Example #31
0
def main(app=None,
         module=None,
         doctype=None,
         verbose=False,
         tests=(),
         force=False,
         profile=False,
         junit_xml_output=None,
         ui_tests=False,
         doctype_list_path=None,
         skip_test_records=False,
         failfast=False):
    global unittest_runner

    if doctype_list_path:
        app, doctype_list_path = doctype_list_path.split(os.path.sep, 1)
        with open(frappe.get_app_path(app, doctype_list_path), 'r') as f:
            doctype = f.read().strip().splitlines()

    if ui_tests:
        print(
            "Selenium testing has been deprecated\nUse bench --site {site_name} run-ui-tests for Cypress tests"
        )

    xmloutput_fh = None
    if junit_xml_output:
        xmloutput_fh = open(junit_xml_output, 'wb')
        unittest_runner = xmlrunner_wrapper(xmloutput_fh)
    else:
        unittest_runner = unittest.TextTestRunner

    try:
        frappe.flags.print_messages = verbose
        frappe.flags.in_test = True

        if not frappe.db:
            frappe.connect()

        # if not frappe.conf.get("db_name").startswith("test_"):
        # 	raise Exception, 'db_name must start with "test_"'

        # workaround! since there is no separate test db
        frappe.clear_cache()
        frappe.utils.scheduler.disable_scheduler()
        set_test_email_config()

        if not frappe.flags.skip_before_tests:
            if verbose:
                print('Running "before_tests" hooks')
            for fn in frappe.get_hooks("before_tests", app_name=app):
                frappe.get_attr(fn)()

        if doctype:
            ret = run_tests_for_doctype(doctype,
                                        verbose,
                                        tests,
                                        force,
                                        profile,
                                        junit_xml_output=junit_xml_output)
        elif module:
            ret = run_tests_for_module(module,
                                       verbose,
                                       tests,
                                       profile,
                                       junit_xml_output=junit_xml_output)
        else:
            ret = run_all_tests(app,
                                verbose,
                                profile,
                                ui_tests,
                                failfast=failfast,
                                junit_xml_output=junit_xml_output)

        if frappe.db: frappe.db.commit()

        # workaround! since there is no separate test db
        frappe.clear_cache()
        return ret

    finally:
        if xmloutput_fh:
            xmloutput_fh.flush()
            xmloutput_fh.close()
			self.add_to_modules_txt()

	def create_modules_folder(self):
		"""Creates a folder `[app]/[module]` and adds `__init__.py`"""
		module_path = frappe.get_app_path(self.app_name, self.name)
		if not os.path.exists(module_path):
			os.mkdir(module_path)
			with open(os.path.join(module_path, "__init__.py"), "w") as f:
				f.write("")

	def add_to_modules_txt(self):
		"""Adds to `[app]/modules.txt`"""
		modules = None
		if not frappe.local.module_app.get(frappe.scrub(self.name)):
			with open(frappe.get_app_path(self.app_name, "modules.txt"), "r") as f:
				content = f.read()
				if not self.name in content.splitlines():
<<<<<<< HEAD
					modules = filter(None, content.splitlines())
=======
					modules = list(filter(None, content.splitlines()))
>>>>>>> 176d241496ede1357a309fa44a037b757a252581
					modules.append(self.name)

			if modules:
				with open(frappe.get_app_path(self.app_name, "modules.txt"), "w") as f:
					f.write("\n".join(modules))

				frappe.clear_cache()
				frappe.setup_module_map()
Example #33
0
def sync_fixtures():
    for app in frappe.get_installed_apps():
        if os.path.exists(frappe.get_app_path(app, "fixtures")):
            for fname in os.listdir(frappe.get_app_path(app, "fixtures")):
                if fname.endswith(".json") or fname.endswith(".csv"):
                    import_doclist(frappe.get_app_path(app, "fixtures", fname))
Example #34
0
def get_json_path(doctype):
    return frappe.get_app_path('erpnext', 'demo', 'data',
                               frappe.scrub(doctype) + '.json')
Example #35
0
def install_country_fixtures(company):
	company_doc = frappe.get_doc("Company", company)
	path = frappe.get_app_path('erpnext', 'regional', frappe.scrub(company_doc.country))
	if os.path.exists(path.encode("utf-8")):
		frappe.get_attr("erpnext.regional.{0}.setup.setup"
			.format(frappe.scrub(company_doc.country)))(company_doc, False)
Example #36
0
    def copy_assets(self):
        """Copy jquery, bootstrap and other assets to files"""

        print "Copying assets..."
        assets_path = os.path.join(self.target, "assets")

        # copy assets from docs
        source_assets = frappe.get_app_path(self.app, "docs", "assets")
        if os.path.exists(source_assets):
            for basepath, folders, files in os.walk(source_assets):
                target_basepath = os.path.join(
                    assets_path, os.path.relpath(basepath, source_assets))

                # make the base folder
                if not os.path.exists(target_basepath):
                    os.makedirs(target_basepath)

                # copy all files in the current folder
                for f in files:
                    shutil.copy(os.path.join(basepath, f),
                                os.path.join(target_basepath, f))

        # make missing folders
        for fname in ("js", "css", "img"):
            path = os.path.join(assets_path, fname)
            if not os.path.exists(path):
                os.makedirs(path)

        copy_files = {
            "js/lib/jquery/jquery.min.js": "js/jquery.min.js",
            "js/lib/bootstrap.min.js": "js/bootstrap.min.js",
            "js/lib/highlight.pack.js": "js/highlight.pack.js",
            "js/docs.js": "js/docs.js",
            "css/bootstrap.css": "css/bootstrap.css",
            "css/font-awesome.css": "css/font-awesome.css",
            "css/docs.css": "css/docs.css",
            "css/hljs.css": "css/hljs.css",
            "css/fonts": "css/fonts",
            "css/octicons": "css/octicons",
            # always overwrite octicons.css to fix the path
            "css/octicons/octicons.css": "css/octicons/octicons.css",
            "images/frappe-bird-grey.svg": "img/frappe-bird-grey.svg",
            "images/favicon.png": "img/favicon.png",
            "images/background.png": "img/background.png",
            "images/smiley.png": "img/smiley.png",
            "images/up.png": "img/up.png"
        }

        for source, target in copy_files.iteritems():
            source_path = frappe.get_app_path("frappe", "public", source)
            if os.path.isdir(source_path):
                if not os.path.exists(os.path.join(assets_path, target)):
                    shutil.copytree(source_path,
                                    os.path.join(assets_path, target))
            else:
                shutil.copy(source_path, os.path.join(assets_path, target))

        # fix path for font-files, background
        files = (
            os.path.join(assets_path, "css", "octicons", "octicons.css"),
            os.path.join(assets_path, "css", "font-awesome.css"),
            os.path.join(assets_path, "css", "docs.css"),
        )

        for path in files:
            with open(path, "r") as css_file:
                text = unicode(css_file.read(), 'utf-8')
            with open(path, "w") as css_file:
                if "docs.css" in path:
                    css_file.write(
                        text.replace("/assets/img/", self.docs_base_url +
                                     '/assets/img/').encode('utf-8'))
                else:
                    css_file.write(
                        text.replace("/assets/frappe/", self.docs_base_url +
                                     '/assets/').encode('utf-8'))
Example #37
0
def fluorine_build_context(context):

    #print "befores fluorine_spacebars_build_context path {}".format(path)
    #if path.find(".") == -1 and not path == "404":
    #print "news fluorine_spacebars_build_context path {}".format(path)
    #fl = frappe.get_doc("Fluorine Reactivity")
    #if fl.fluorine_base_template and fl.fluorine_base_template.lower() != "default":
    #	app_base_template = fl.fluorine_base_template
    #else:
    #	app_base_template = frappe.get_hooks("base_template")
    #	if not app_base_template:
    #		app_base_template = "templates/base.html"

    #if context.base_template_path == app_base_template:

    #if not context.spacebars_data:
    #	context.spacebars_data = {}
    #print "context data path in override {}".format(context.data)
    #context.update(context.data or {})
    apps = frappe.get_installed_apps()  #[::-1]
    #apps.remove("fluorine")
    name_templates = []
    spacebars_templates = {}

    for app in apps:
        #print "app {}".format(app)
        pathname = frappe.get_app_path(app)  #get_package_path(app, "", "")
        if pathname:
            for root, dirs, files in os.walk(
                    os.path.join(pathname, "templates", "react")):
                for file in files:
                    if file.endswith(".html"):
                        #print "app is {} path is {}".format(app, os.path.join(os.path.relpath(root, pathname), file))
                        #print(os.path.join(root, file[:-5] + ".py"))
                        #filename = os.path.join(root, file)
                        context.spacebars_template = os.path.join(
                            os.path.relpath(root, pathname), file)
                        if os.path.exists(os.path.join(root,
                                                       file[:-5] + ".py")):
                            controller_path = os.path.join(
                                app, context.spacebars_template).replace(
                                    os.path.sep, ".")[:-5]
                            #print "app_path {}".format(controller_path + ".py")
                            module = frappe.get_module(controller_path)
                            if module:
                                if hasattr(module, "get_context"):
                                    ret = module.get_context(context)
                                    if ret:
                                        context.update(ret)
                                if hasattr(module, "get_children"):
                                    context.get_children = module.get_children
                        #heritage
                        out = fluorine_render_blocks(context)
                        #context.spacebars_data.update(out)
                        print "out {}".format(out)
                        #print "context teste123 {} out {}".format(context.teste123, out.get("teste123", None))
                        #print frappe.utils.pprint_dict(out)
                        spacebars_templates.update(out)
                        #for name in out:
                        #	name_templates.append(name)
                        context.update(out)
                        #print "new spacebars_data {}".format(context)
    #context.data.update(context.spacebars_data or {})


#print "In fluorine_spacebars_build_context"
    compiled_spacebars_js = compile_spacebars_templates(spacebars_templates)
    arr = compiled_spacebars_js.split("__templates__\n")
    arr.insert(0, "(function(){\n")
    arr.append("})();\n")

    hooks_js = get_js_to_client()

    context.compiled_spacebars_js = arr

    context.update(hooks_js)
    #print "A compilar templates \n{}".format(context.compiled_spacebars_js)

    return context
Example #38
0
def install(country=None):
    records = [
        # domains
        {
            'doctype': 'Domain',
            'domain': 'Distribution'
        },
        {
            'doctype': 'Domain',
            'domain': 'Manufacturing'
        },
        {
            'doctype': 'Domain',
            'domain': 'Retail'
        },
        {
            'doctype': 'Domain',
            'domain': 'Services'
        },
        {
            'doctype': 'Domain',
            'domain': 'Education'
        },
        {
            'doctype': 'Domain',
            'domain': 'Healthcare'
        },
        {
            'doctype': 'Domain',
            'domain': 'Agriculture'
        },
        {
            'doctype': 'Domain',
            'domain': 'Non Profit'
        },

        # ensure at least an empty Address Template exists for this Country
        {
            'doctype': "Address Template",
            "country": country
        },

        # item group
        {
            'doctype': 'Item Group',
            'item_group_name': _('All Item Groups'),
            'is_group': 1,
            'parent_item_group': ''
        },
        {
            'doctype': 'Item Group',
            'item_group_name': _('Products'),
            'is_group': 0,
            'parent_item_group': _('All Item Groups'),
            "show_in_website": 1
        },
        {
            'doctype': 'Item Group',
            'item_group_name': _('Raw Material'),
            'is_group': 0,
            'parent_item_group': _('All Item Groups')
        },
        {
            'doctype': 'Item Group',
            'item_group_name': _('Services'),
            'is_group': 0,
            'parent_item_group': _('All Item Groups')
        },
        {
            'doctype': 'Item Group',
            'item_group_name': _('Sub Assemblies'),
            'is_group': 0,
            'parent_item_group': _('All Item Groups')
        },
        {
            'doctype': 'Item Group',
            'item_group_name': _('Consumable'),
            'is_group': 0,
            'parent_item_group': _('All Item Groups')
        },

        # salary component
        {
            'doctype': 'Salary Component',
            'salary_component': _('Income Tax'),
            'description': _('Income Tax'),
            'type': 'Deduction',
            'is_income_tax_component': 1
        },
        {
            'doctype': 'Salary Component',
            'salary_component': _('Basic'),
            'description': _('Basic'),
            'type': 'Earning'
        },
        {
            'doctype': 'Salary Component',
            'salary_component': _('Arrear'),
            'description': _('Arrear'),
            'type': 'Earning'
        },
        {
            'doctype': 'Salary Component',
            'salary_component': _('Leave Encashment'),
            'description': _('Leave Encashment'),
            'type': 'Earning'
        },

        # expense claim type
        {
            'doctype': 'Expense Claim Type',
            'name': _('Calls'),
            'expense_type': _('Calls')
        },
        {
            'doctype': 'Expense Claim Type',
            'name': _('Food'),
            'expense_type': _('Food')
        },
        {
            'doctype': 'Expense Claim Type',
            'name': _('Medical'),
            'expense_type': _('Medical')
        },
        {
            'doctype': 'Expense Claim Type',
            'name': _('Others'),
            'expense_type': _('Others')
        },
        {
            'doctype': 'Expense Claim Type',
            'name': _('Travel'),
            'expense_type': _('Travel')
        },

        # leave type
        {
            'doctype': 'Leave Type',
            'leave_type_name': _('Casual Leave'),
            'name': _('Casual Leave'),
            'allow_encashment': 1,
            'is_carry_forward': 1,
            'max_continuous_days_allowed': '3',
            'include_holiday': 1
        },
        {
            'doctype': 'Leave Type',
            'leave_type_name': _('Compensatory Off'),
            'name': _('Compensatory Off'),
            'allow_encashment': 0,
            'is_carry_forward': 0,
            'include_holiday': 1,
            'is_compensatory': 1
        },
        {
            'doctype': 'Leave Type',
            'leave_type_name': _('Sick Leave'),
            'name': _('Sick Leave'),
            'allow_encashment': 0,
            'is_carry_forward': 0,
            'include_holiday': 1
        },
        {
            'doctype': 'Leave Type',
            'leave_type_name': _('Privilege Leave'),
            'name': _('Privilege Leave'),
            'allow_encashment': 0,
            'is_carry_forward': 0,
            'include_holiday': 1
        },
        {
            'doctype': 'Leave Type',
            'leave_type_name': _('Leave Without Pay'),
            'name': _('Leave Without Pay'),
            'allow_encashment': 0,
            'is_carry_forward': 0,
            'is_lwp': 1,
            'include_holiday': 1
        },

        # Employment Type
        {
            'doctype': 'Employment Type',
            'employee_type_name': _('Full-time')
        },
        {
            'doctype': 'Employment Type',
            'employee_type_name': _('Part-time')
        },
        {
            'doctype': 'Employment Type',
            'employee_type_name': _('Probation')
        },
        {
            'doctype': 'Employment Type',
            'employee_type_name': _('Contract')
        },
        {
            'doctype': 'Employment Type',
            'employee_type_name': _('Commission')
        },
        {
            'doctype': 'Employment Type',
            'employee_type_name': _('Piecework')
        },
        {
            'doctype': 'Employment Type',
            'employee_type_name': _('Intern')
        },
        {
            'doctype': 'Employment Type',
            'employee_type_name': _('Apprentice')
        },

        # Stock Entry Type
        {
            'doctype': 'Stock Entry Type',
            'name': 'Material Issue',
            'purpose': 'Material Issue'
        },
        {
            'doctype': 'Stock Entry Type',
            'name': 'Material Receipt',
            'purpose': 'Material Receipt'
        },
        {
            'doctype': 'Stock Entry Type',
            'name': 'Material Transfer',
            'purpose': 'Material Transfer'
        },
        {
            'doctype': 'Stock Entry Type',
            'name': 'Manufacture',
            'purpose': 'Manufacture'
        },
        {
            'doctype': 'Stock Entry Type',
            'name': 'Repack',
            'purpose': 'Repack'
        },
        {
            'doctype': 'Stock Entry Type',
            'name': 'Send to Subcontractor',
            'purpose': 'Send to Subcontractor'
        },
        {
            'doctype': 'Stock Entry Type',
            'name': 'Material Transfer for Manufacture',
            'purpose': 'Material Transfer for Manufacture'
        },
        {
            'doctype': 'Stock Entry Type',
            'name': 'Material Consumption for Manufacture',
            'purpose': 'Material Consumption for Manufacture'
        },

        # Designation
        {
            'doctype': 'Designation',
            'designation_name': _('CEO')
        },
        {
            'doctype': 'Designation',
            'designation_name': _('Manager')
        },
        {
            'doctype': 'Designation',
            'designation_name': _('Analyst')
        },
        {
            'doctype': 'Designation',
            'designation_name': _('Engineer')
        },
        {
            'doctype': 'Designation',
            'designation_name': _('Accountant')
        },
        {
            'doctype': 'Designation',
            'designation_name': _('Secretary')
        },
        {
            'doctype': 'Designation',
            'designation_name': _('Associate')
        },
        {
            'doctype': 'Designation',
            'designation_name': _('Administrative Officer')
        },
        {
            'doctype': 'Designation',
            'designation_name': _('Business Development Manager')
        },
        {
            'doctype': 'Designation',
            'designation_name': _('HR Manager')
        },
        {
            'doctype': 'Designation',
            'designation_name': _('Project Manager')
        },
        {
            'doctype': 'Designation',
            'designation_name': _('Head of Marketing and Sales')
        },
        {
            'doctype': 'Designation',
            'designation_name': _('Software Developer')
        },
        {
            'doctype': 'Designation',
            'designation_name': _('Designer')
        },
        {
            'doctype': 'Designation',
            'designation_name': _('Researcher')
        },

        # territory: with two default territories, one for home country and one named Rest of the World
        {
            'doctype': 'Territory',
            'territory_name': _('All Territories'),
            'is_group': 1,
            'name': _('All Territories'),
            'parent_territory': ''
        },
        {
            'doctype': 'Territory',
            'territory_name': country.replace("'", ""),
            'is_group': 0,
            'parent_territory': _('All Territories')
        },
        {
            'doctype': 'Territory',
            'territory_name': _("Rest Of The World"),
            'is_group': 0,
            'parent_territory': _('All Territories')
        },

        # customer group
        {
            'doctype': 'Customer Group',
            'customer_group_name': _('All Customer Groups'),
            'is_group': 1,
            'name': _('All Customer Groups'),
            'parent_customer_group': ''
        },
        {
            'doctype': 'Customer Group',
            'customer_group_name': _('Individual'),
            'is_group': 0,
            'parent_customer_group': _('All Customer Groups')
        },
        {
            'doctype': 'Customer Group',
            'customer_group_name': _('Commercial'),
            'is_group': 0,
            'parent_customer_group': _('All Customer Groups')
        },
        {
            'doctype': 'Customer Group',
            'customer_group_name': _('Non Profit'),
            'is_group': 0,
            'parent_customer_group': _('All Customer Groups')
        },
        {
            'doctype': 'Customer Group',
            'customer_group_name': _('Government'),
            'is_group': 0,
            'parent_customer_group': _('All Customer Groups')
        },

        # supplier group
        {
            'doctype': 'Supplier Group',
            'supplier_group_name': _('All Supplier Groups'),
            'is_group': 1,
            'name': _('All Supplier Groups'),
            'parent_supplier_group': ''
        },
        {
            'doctype': 'Supplier Group',
            'supplier_group_name': _('Services'),
            'is_group': 0,
            'parent_supplier_group': _('All Supplier Groups')
        },
        {
            'doctype': 'Supplier Group',
            'supplier_group_name': _('Local'),
            'is_group': 0,
            'parent_supplier_group': _('All Supplier Groups')
        },
        {
            'doctype': 'Supplier Group',
            'supplier_group_name': _('Raw Material'),
            'is_group': 0,
            'parent_supplier_group': _('All Supplier Groups')
        },
        {
            'doctype': 'Supplier Group',
            'supplier_group_name': _('Electrical'),
            'is_group': 0,
            'parent_supplier_group': _('All Supplier Groups')
        },
        {
            'doctype': 'Supplier Group',
            'supplier_group_name': _('Hardware'),
            'is_group': 0,
            'parent_supplier_group': _('All Supplier Groups')
        },
        {
            'doctype': 'Supplier Group',
            'supplier_group_name': _('Pharmaceutical'),
            'is_group': 0,
            'parent_supplier_group': _('All Supplier Groups')
        },
        {
            'doctype': 'Supplier Group',
            'supplier_group_name': _('Distributor'),
            'is_group': 0,
            'parent_supplier_group': _('All Supplier Groups')
        },

        # Sales Person
        {
            'doctype': 'Sales Person',
            'sales_person_name': _('Sales Team'),
            'is_group': 1,
            "parent_sales_person": ""
        },

        # Mode of Payment
        {
            'doctype':
            'Mode of Payment',
            'mode_of_payment':
            'Check' if country == "United States" else _('Cheque'),
            'type':
            'Bank'
        },
        {
            'doctype': 'Mode of Payment',
            'mode_of_payment': _('Cash'),
            'type': 'Cash'
        },
        {
            'doctype': 'Mode of Payment',
            'mode_of_payment': _('Credit Card'),
            'type': 'Bank'
        },
        {
            'doctype': 'Mode of Payment',
            'mode_of_payment': _('Wire Transfer'),
            'type': 'Bank'
        },
        {
            'doctype': 'Mode of Payment',
            'mode_of_payment': _('Bank Draft'),
            'type': 'Bank'
        },

        # Activity Type
        {
            'doctype': 'Activity Type',
            'activity_type': _('Planning')
        },
        {
            'doctype': 'Activity Type',
            'activity_type': _('Research')
        },
        {
            'doctype': 'Activity Type',
            'activity_type': _('Proposal Writing')
        },
        {
            'doctype': 'Activity Type',
            'activity_type': _('Execution')
        },
        {
            'doctype': 'Activity Type',
            'activity_type': _('Communication')
        },
        {
            'doctype':
            "Item Attribute",
            "attribute_name":
            _("Size"),
            "item_attribute_values": [{
                "attribute_value": _("Extra Small"),
                "abbr": "XS"
            }, {
                "attribute_value": _("Small"),
                "abbr": "S"
            }, {
                "attribute_value": _("Medium"),
                "abbr": "M"
            }, {
                "attribute_value": _("Large"),
                "abbr": "L"
            }, {
                "attribute_value": _("Extra Large"),
                "abbr": "XL"
            }]
        },
        {
            'doctype':
            "Item Attribute",
            "attribute_name":
            _("Colour"),
            "item_attribute_values": [{
                "attribute_value": _("Red"),
                "abbr": "RED"
            }, {
                "attribute_value": _("Green"),
                "abbr": "GRE"
            }, {
                "attribute_value": _("Blue"),
                "abbr": "BLU"
            }, {
                "attribute_value": _("Black"),
                "abbr": "BLA"
            }, {
                "attribute_value": _("White"),
                "abbr": "WHI"
            }]
        },

        # Issue Priority
        {
            'doctype': 'Issue Priority',
            'name': _('Low')
        },
        {
            'doctype': 'Issue Priority',
            'name': _('Medium')
        },
        {
            'doctype': 'Issue Priority',
            'name': _('High')
        },

        #Job Applicant Source
        {
            'doctype': 'Job Applicant Source',
            'source_name': _('Website Listing')
        },
        {
            'doctype': 'Job Applicant Source',
            'source_name': _('Walk In')
        },
        {
            'doctype': 'Job Applicant Source',
            'source_name': _('Employee Referral')
        },
        {
            'doctype': 'Job Applicant Source',
            'source_name': _('Campaign')
        },
        {
            'doctype': "Email Account",
            "email_id": "*****@*****.**",
            "append_to": "Opportunity"
        },
        {
            'doctype': "Email Account",
            "email_id": "*****@*****.**",
            "append_to": "Issue"
        },
        {
            'doctype': "Email Account",
            "email_id": "*****@*****.**",
            "append_to": "Job Applicant"
        },
        {
            'doctype': "Party Type",
            "party_type": "Customer",
            "account_type": "Receivable"
        },
        {
            'doctype': "Party Type",
            "party_type": "Supplier",
            "account_type": "Payable"
        },
        {
            'doctype': "Party Type",
            "party_type": "Employee",
            "account_type": "Payable"
        },
        {
            'doctype': "Party Type",
            "party_type": "Member",
            "account_type": "Receivable"
        },
        {
            'doctype': "Party Type",
            "party_type": "Shareholder",
            "account_type": "Payable"
        },
        {
            'doctype': "Party Type",
            "party_type": "Student",
            "account_type": "Receivable"
        },
        {
            'doctype': "Opportunity Type",
            "name": "Hub"
        },
        {
            'doctype': "Opportunity Type",
            "name": _("Sales")
        },
        {
            'doctype': "Opportunity Type",
            "name": _("Support")
        },
        {
            'doctype': "Opportunity Type",
            "name": _("Maintenance")
        },
        {
            'doctype': "Project Type",
            "project_type": "Internal"
        },
        {
            'doctype': "Project Type",
            "project_type": "External"
        },
        {
            'doctype': "Project Type",
            "project_type": "Other"
        },
        {
            "doctype": "Offer Term",
            "offer_term": _("Date of Joining")
        },
        {
            "doctype": "Offer Term",
            "offer_term": _("Annual Salary")
        },
        {
            "doctype": "Offer Term",
            "offer_term": _("Probationary Period")
        },
        {
            "doctype": "Offer Term",
            "offer_term": _("Employee Benefits")
        },
        {
            "doctype": "Offer Term",
            "offer_term": _("Working Hours")
        },
        {
            "doctype": "Offer Term",
            "offer_term": _("Stock Options")
        },
        {
            "doctype": "Offer Term",
            "offer_term": _("Department")
        },
        {
            "doctype": "Offer Term",
            "offer_term": _("Job Description")
        },
        {
            "doctype": "Offer Term",
            "offer_term": _("Responsibilities")
        },
        {
            "doctype": "Offer Term",
            "offer_term": _("Leaves per Year")
        },
        {
            "doctype": "Offer Term",
            "offer_term": _("Notice Period")
        },
        {
            "doctype": "Offer Term",
            "offer_term": _("Incentives")
        },
        {
            'doctype': "Print Heading",
            'print_heading': _("Credit Note")
        },
        {
            'doctype': "Print Heading",
            'print_heading': _("Debit Note")
        },

        # Assessment Group
        {
            'doctype': 'Assessment Group',
            'assessment_group_name': _('All Assessment Groups'),
            'is_group': 1,
            'parent_assessment_group': ''
        },

        # Share Management
        {
            "doctype": "Share Type",
            "title": _("Equity")
        },
        {
            "doctype": "Share Type",
            "title": _("Preference")
        },

        # Market Segments
        {
            "doctype": "Market Segment",
            "market_segment": _("Lower Income")
        },
        {
            "doctype": "Market Segment",
            "market_segment": _("Middle Income")
        },
        {
            "doctype": "Market Segment",
            "market_segment": _("Upper Income")
        },

        # Sales Stages
        {
            "doctype": "Sales Stage",
            "stage_name": _("Prospecting")
        },
        {
            "doctype": "Sales Stage",
            "stage_name": _("Qualification")
        },
        {
            "doctype": "Sales Stage",
            "stage_name": _("Needs Analysis")
        },
        {
            "doctype": "Sales Stage",
            "stage_name": _("Value Proposition")
        },
        {
            "doctype": "Sales Stage",
            "stage_name": _("Identifying Decision Makers")
        },
        {
            "doctype": "Sales Stage",
            "stage_name": _("Perception Analysis")
        },
        {
            "doctype": "Sales Stage",
            "stage_name": _("Proposal/Price Quote")
        },
        {
            "doctype": "Sales Stage",
            "stage_name": _("Negotiation/Review")
        },

        # Warehouse Type
        {
            'doctype': 'Warehouse Type',
            'name': 'Transit'
        },
    ]

    from erpbee.setup.setup_wizard.data.industry_type import get_industry_types
    records += [{
        "doctype": "Industry Type",
        "industry": d
    } for d in get_industry_types()]
    # records += [{"doctype":"Operation", "operation": d} for d in get_operations()]
    records += [{
        'doctype': 'Lead Source',
        'source_name': _(d)
    } for d in default_lead_sources]

    records += [{
        'doctype': 'Sales Partner Type',
        'sales_partner_type': _(d)
    } for d in default_sales_partner_type]

    base_path = frappe.get_app_path("erpbee", "hr", "doctype")
    response = frappe.read_file(
        os.path.join(
            base_path,
            "leave_application/leave_application_email_template.html"))

    records += [{'doctype': 'Email Template', 'name': _("Leave Approval Notification"), 'response': response,\
     'subject': _("Leave Approval Notification"), 'owner': frappe.session.user}]

    records += [{'doctype': 'Email Template', 'name': _("Leave Status Notification"), 'response': response,\
     'subject': _("Leave Status Notification"), 'owner': frappe.session.user}]

    base_path = frappe.get_app_path("erpbee", "stock", "doctype")
    response = frappe.read_file(
        os.path.join(base_path,
                     "delivery_trip/dispatch_notification_template.html"))

    records += [{'doctype': 'Email Template', 'name': _("Dispatch Notification"), 'response': response,\
     'subject': _("Your order is out for delivery!"), 'owner': frappe.session.user}]

    # Records for the Supplier Scorecard
    from erpbee.buying.doctype.supplier_scorecard.supplier_scorecard import make_default_records

    make_default_records()
    make_records(records)
    set_up_address_templates(default_country=country)
    set_more_defaults()
    update_global_search_doctypes()
Example #39
0
    def __init__(self):
        self._funcs_docs = tree()
        super(JSInterpreter, self).__init__()

        # load javascript path
        for app in frappe.get_installed_apps():
            for hook in frappe.get_hooks('studio_library_path', app_name=app):
                self.loader.register_path(frappe.get_app_path(app, hook))

        # load functions
        _gbl = tree()
        replacements = {}
        for attr in frappe.get_hooks('studio_functions', []):
            paths = []
            if isinstance(attr, dict):
                for key, value in attr.items():
                    attr, expand = get_attr(value)
                    if not expand:
                        paths.append(key)
                        self.export_function(key, attr)
                    else:
                        base_path = key
                        for fn, item in inspect.getmembers(
                                attr, is_module_function(base_path)):
                            key = '{0}.{1}'.format(base_path, fn)
                            self.export_function(key, item)
                            paths.append(key)

            elif isinstance(attr, (list, tuple, set)):
                raise frappe.ValidationError(
                    'Invalid hook format {}, should be ("list" or "dict") not "{}"'
                    .format(frappe.as_json(list(attr)),
                            type(attr).__name__))
            else:
                obj, expand = get_attr(attr)

                if not expand:
                    paths.append(attr)
                    self.export_function(attr, obj)
                else:
                    base_path = attr
                    for fn, item in inspect.getmembers(
                            obj, is_module_function(base_path)):
                        attr = '{0}.{1}'.format(base_path, fn)
                        self.export_function(attr, item)
                        paths.append(attr)

            for path in paths:
                parts = path.split('.')
                fn = parts.pop()
                actual = None
                for part in parts:
                    actual = (actual or _gbl)[part]
                actual[fn] = '{{{0}}}'.format(path.replace('.', '_'))
                replacements[path.replace(
                    '.', '_'
                )] = '''function() {{ return call_python("{0}", as_list(arguments)); }}'''.format(
                    path)

        self.evaljs('''
			function as_list(a){ var args = []; for(var i = 0; i < a.length; i++){ args.push(a[i]); } return args; }
			function enable_document_syncronization(){ ctx.enabled_document_syncronization = true; }
			function disable_document_syncronization(){ ctx.enabled_document_syncronization = false; }
			function add_child(field, child){
				if (!ctx.enabled_document_syncronization) return;
				var df = frappe.utils.filter_dict(ctx.meta.fields, {'fieldname': field, 'fieldtype': 'Table'});
				if (!df) return;
				df = df[0];
				if (!Array.isArray(doc[df.fieldname])) doc[df.fieldname] = [];
				if (!child.doctype) child.doctype = df.options;
				if (!child.parenttype) child.parenttype = doc.doctype;
				if (!child.paerentfield) child.parentfield = df.fieldname;
				doc[df.fieldname].push(child);
			}
		''')

        JS_GLOBALS = []

        for k in _gbl.keys():
            JS_GLOBALS_PART = k + ' = ' + json.dumps(_gbl[k], indent=2) + ';'

            for rk, v in replacements.items():
                if not rk.startswith(k + '_'):
                    continue
                JS_GLOBALS_PART = JS_GLOBALS_PART.replace('"{' + rk + '}"', v)
        JS_GLOBALS.append(JS_GLOBALS_PART)
        #frappe.msgprint('<pre>{0}</pre>'.format('\n'.join(JS_GLOBALS)))
        self.evaljs('\n'.join(JS_GLOBALS))