コード例 #1
0
	def test_confirm_payment(self):
		razorpay_payment_id = "test_pay_{0}".format(frappe.generate_hash(length=14))
		razorpay_payment = make_payment(razorpay_payment_id=razorpay_payment_id,
			options=json.dumps(data["options"]))
			
		self.assertRaises(InvalidRequest, razorpay_payment.insert)
		
		razorpay_settings = frappe.get_doc("Razorpay Settings")
		razorpay_settings.update(data["razorpay_settings"])
		
		razorpay_payment_id = "test_pay_{0}".format(frappe.generate_hash(length=14))
		
		razorpay_payment = make_payment(razorpay_payment_id=razorpay_payment_id,
			options=json.dumps(data["options"]))
			
		razorpay_payment.flags.is_sandbox = True
		razorpay_payment.sanbox_response = data["sanbox_response"]
		razorpay_payment.sanbox_response.update({
			"id": razorpay_payment_id,
			"status": "authorized"
		})
		
		razorpay_payment.insert(ignore_permissions=True)
		
		razorpay_payment_status = frappe.db.get_value("Razorpay Payment", razorpay_payment_id, "status")
		
		self.assertEquals(razorpay_payment_status, "Authorized")
コード例 #2
0
ファイル: pdf.py プロジェクト: Alphamonarch/frappe
def get_pdf(html, options=None):
	if not options:
		options = {}

	options.update({
		"print-media-type": None,
		"background": None,
		"images": None,
		'margin-top': '15mm',
		'margin-right': '15mm',
		'margin-bottom': '15mm',
		'margin-left': '15mm',
		'encoding': "UTF-8",
		'quiet': None,
		'no-outline': None
	})

	if not options.get("page-size"):
		options['page-size'] = frappe.db.get_single_value("Print Settings", "pdf_page_size") or "A4"

	html = scrub_urls(html)
	fname = os.path.join("/tmp", frappe.generate_hash() + ".pdf")
	pdfkit.from_string(html, fname, options=options or {})

	with open(fname, "rb") as fileobj:
		filedata = fileobj.read()

	os.remove(fname)

	return filedata
コード例 #3
0
ファイル: sessions.py プロジェクト: olhonko/frappe
    def start(self):
        """start a new session"""
        # generate sid
        if self.user == "Guest":
            sid = "Guest"
        else:
            sid = frappe.generate_hash()

        self.data.user = self.user
        self.data.sid = sid
        self.data.data.user = self.user
        self.data.data.session_ip = frappe.local.request_ip
        if self.user != "Guest":
            self.data.data.update(
                {
                    "last_updated": frappe.utils.now(),
                    "session_expiry": get_expiry_period(self.device),
                    "full_name": self.full_name,
                    "user_type": self.user_type,
                    "device": self.device,
                    "session_country": get_geo_ip_country(frappe.local.request_ip),
                }
            )

            # insert session
        if self.user != "Guest":
            self.insert_session_record()

            # update user
            frappe.db.sql(
                """UPDATE tabUser SET last_login = %s, last_ip = %s
				where name=%s""",
                (frappe.utils.now(), frappe.local.request_ip, self.data["user"]),
            )
            frappe.db.commit()
コード例 #4
0
ファイル: naming.py プロジェクト: JiShangShiDai/frappe
def make_autoname(key='', doctype='', doc=''):
	"""
   Creates an autoname from the given key:

   **Autoname rules:**

         * The key is separated by '.'
         * '####' represents a series. The string before this part becomes the prefix:
            Example: ABC.#### creates a series ABC0001, ABC0002 etc
         * 'MM' represents the current month
         * 'YY' and 'YYYY' represent the current year


   *Example:*

         * DE/./.YY./.MM./.##### will create a series like
           DE/09/01/0001 where 09 is the year, 01 is the month and 0001 is the series
	"""
	if key=="hash":
		return frappe.generate_hash(doctype, 10)

	if not "#" in key:
		key = key + ".#####"
	elif not "." in key:
		frappe.throw(_("Invalid naming series (. missing)") + (_(" for {0}").format(doctype) if doctype else ""))

	parts = key.split('.')
	n = parse_naming_series(parts, doctype, doc)
	return n
コード例 #5
0
ファイル: sessions.py プロジェクト: 81552433qqcom/frappe
	def start(self):
		"""start a new session"""
		# generate sid
		if self.user=='Guest':
			sid = 'Guest'
		else:
			sid = frappe.generate_hash()

		self.data['user'] = self.user
		self.data['sid'] = sid
		self.data['data']['user'] = self.user
		self.data['data']['session_ip'] = frappe.get_request_header('REMOTE_ADDR')
		if self.user != "Guest":
			self.data['data']['last_updated'] = frappe.utils.now()
			self.data['data']['session_expiry'] = get_expiry_period()
		self.data['data']['session_country'] = get_geo_ip_country(frappe.get_request_header('REMOTE_ADDR'))

		# insert session
		if self.user!="Guest":
			frappe.db.begin()
			self.insert_session_record()

			# update user
			frappe.db.sql("""UPDATE tabUser SET last_login = %s, last_ip = %s
				where name=%s""", (frappe.utils.now(), frappe.get_request_header('REMOTE_ADDR'), self.data['user']))
			frappe.db.commit()
コード例 #6
0
ファイル: user.py プロジェクト: britlog/frappe
	def validate(self):
		self.check_demo()

		# clear new password
		self.__new_password = self.new_password
		self.new_password = ""

		if not frappe.flags.in_test:
			self.password_strength_test()

		if self.name not in STANDARD_USERS:
			self.validate_email_type(self.email)
			self.validate_email_type(self.name)
		self.add_system_manager_role()
		self.set_system_user()
		self.set_full_name()
		self.check_enable_disable()
		self.ensure_unique_roles()
		self.remove_all_roles_for_guest()
		self.validate_username()
		self.remove_disabled_roles()
		self.validate_user_email_inbox()
		ask_pass_update()
		self.validate_roles()
		self.validate_user_image()

		if self.language == "Loading...":
			self.language = None

		if (self.name not in ["Administrator", "Guest"]) and (not self.frappe_userid):
			self.frappe_userid = frappe.generate_hash(length=39)
コード例 #7
0
ファイル: pdf.py プロジェクト: frappe/frappe
def get_pdf(html, options=None, output=None):
    html = scrub_urls(html)
    html, options = prepare_options(html, options)
    fname = os.path.join("/tmp", "frappe-pdf-{0}.pdf".format(frappe.generate_hash()))

    try:
        pdfkit.from_string(html, fname, options=options or {})
        if output:
            append_pdf(PdfFileReader(file(fname, "rb")), output)
        else:
            with open(fname, "rb") as fileobj:
                filedata = fileobj.read()

    except IOError, e:
        if (
            "ContentNotFoundError" in e.message
            or "ContentOperationNotPermittedError" in e.message
            or "UnknownContentError" in e.message
            or "RemoteHostClosedError" in e.message
        ):

            # allow pdfs with missing images if file got created
            if os.path.exists(fname):
                with open(fname, "rb") as fileobj:
                    filedata = fileobj.read()

            else:
                frappe.throw(_("PDF generation failed because of broken image links"))
        else:
            raise
コード例 #8
0
ファイル: print_format.py プロジェクト: ESS-LLP/frappe
def print_by_server(doctype, name, print_format=None, doc=None, no_letterhead=0):
	print_settings = frappe.get_doc("Print Settings")
	try:
		import cups
	except ImportError:
		frappe.throw("You need to install pycups to use this feature!")
		return
	try:
		cups.setServer(print_settings.server_ip)
		cups.setPort(print_settings.port)
		conn = cups.Connection()
		output = PdfFileWriter()
		output = frappe.get_print(doctype, name, print_format, doc=doc, no_letterhead=no_letterhead, as_pdf = True, output = output)
		file = os.path.join("/", "tmp", "frappe-pdf-{0}.pdf".format(frappe.generate_hash()))
		output.write(open(file,"wb"))
		conn.printFile(print_settings.printer_name,file , name, {})
	except IOError as e:
		if ("ContentNotFoundError" in e.message
			or "ContentOperationNotPermittedError" in e.message
			or "UnknownContentError" in e.message
			or "RemoteHostClosedError" in e.message):
			frappe.throw(_("PDF generation failed"))
	except cups.IPPError:
		frappe.throw(_("Printing failed"))
	finally:
		cleanup(file,{})
コード例 #9
0
def insert_user_social_login(user, modified_by, provider, idx, userid=None, username=None):
	source_cols = get_standard_cols()

	creation_time = frappe.utils.get_datetime_str(frappe.utils.get_datetime())
	values = [
		frappe.generate_hash(length=10),
		creation_time,
		creation_time,
		user,
		modified_by,
		user,
		"User",
		"social_logins",
		cstr(idx),
		provider
	]

	if userid:
		source_cols.append("userid")
		values.append(userid)

	if username:
		source_cols.append("username")
		values.append(username)


	query = """INSERT INTO `tabUser Social Login` ({source_cols})
		VALUES ({values})
	""".format(
		source_cols = "`" + "`, `".join(source_cols) + "`",
		values= "'" + "', '".join([frappe.db.escape(d) for d in values]) + "'"
	)

	frappe.db.sql(query)
コード例 #10
0
ファイル: pdf.py プロジェクト: Alisha-Varkey/Saloon_frappe
def get_pdf(html, options=None):
	if not options:
		options = {}

	options.update({
		"print-media-type": None,
		"background": None,
		"images": None,
		'margin-top': '15mm',
		'margin-right': '15mm',
		'margin-bottom': '15mm',
		'margin-left': '15mm',
		'encoding': "UTF-8",
		'quiet': None,
		'no-outline': None
	})

	if not options.get("page-size"):
		options['page-size'] = frappe.db.get_single_value("Print Settings", "pdf_page_size") or "A4"

	html = scrub_urls(html)
	fname = os.path.join("/tmp", frappe.generate_hash() + ".pdf")
	try:
		pdfkit.from_string(html, fname, options=options or {})
	except IOError, e:
		if "ContentNotFoundError" in e.message:
			frappe.throw(_("PDF generation failed because of broken image links"))
		else:
			raise
コード例 #11
0
ファイル: sessions.py プロジェクト: vrms/frappe
	def start(self):
		"""start a new session"""
		# generate sid
		if self.user=='Guest':
			sid = 'Guest'
		else:
			sid = frappe.generate_hash()

		self.data.user = self.user
		self.data.sid = sid
		self.data.data.user = self.user
		self.data.data.session_ip = frappe.local.request_ip
		if self.user != "Guest":
			self.data.data.update({
				"last_updated": frappe.utils.now(),
				"session_expiry": get_expiry_period(self.device),
				"full_name": self.full_name,
				"user_type": self.user_type,
				"device": self.device,
				"session_country": get_geo_ip_country(frappe.local.request_ip) if frappe.local.request_ip else None,
			})

		# insert session
		if self.user!="Guest":
			self.insert_session_record()

			# update user
			frappe.db.sql("""UPDATE tabUser SET last_login = %(now)s, last_ip = %(ip)s, last_active = %(now)s
				where name=%(name)s""", {
					"now": frappe.utils.now(),
					"ip": frappe.local.request_ip,
					"name": self.data['user']
				})

			frappe.db.commit()
コード例 #12
0
ファイル: sessions.py プロジェクト: BIANBS/frappe
    def start(self):
        """start a new session"""
        # generate sid
        if self.user == "Guest":
            sid = "Guest"
        else:
            sid = frappe.generate_hash()

        self.data["user"] = self.user
        self.data["sid"] = sid
        self.data["data"]["user"] = self.user
        self.data["data"]["session_ip"] = frappe.get_request_header("REMOTE_ADDR")
        if self.user != "Guest":
            self.data["data"]["last_updated"] = frappe.utils.now()
            self.data["data"]["session_expiry"] = get_expiry_period()
        self.data["data"]["session_country"] = get_geo_ip_country(frappe.get_request_header("REMOTE_ADDR"))

        # insert session
        if self.user != "Guest":
            frappe.db.begin()
            self.insert_session_record()

            # update user
            frappe.db.sql(
                """UPDATE tabUser SET last_login = %s, last_ip = %s
				where name=%s""",
                (frappe.utils.now(), frappe.get_request_header("REMOTE_ADDR"), self.data["user"]),
            )
            frappe.db.commit()
コード例 #13
0
ファイル: oauth.py プロジェクト: frappe/frappe
def login_oauth_user(data=None, provider=None, state=None, email_id=None, key=None, generate_login_token=False):
    # NOTE: This could lead to security issue as the signed in user can type any email address in complete_signup
    # if email_id and key:
    # 	data = json.loads(frappe.db.get_temp(key))
    # 	# What if data is missing because of an invalid key
    # 	data["email"] = email_id
    #
    # elif not (data.get("email") and get_first_name(data)) and not frappe.db.exists("User", data.get("email")):
    # 	# ask for user email
    # 	key = frappe.db.set_temp(json.dumps(data))
    # 	frappe.db.commit()
    # 	frappe.local.response["type"] = "redirect"
    # 	frappe.local.response["location"] = "/complete_signup?key=" + key
    # 	return

    # json.loads data and state
    if isinstance(data, basestring):
        data = json.loads(data)

    if isinstance(state, basestring):
        state = json.loads(state)

    if not (state and state["token"]):
        frappe.respond_as_web_page(_("Invalid Request"), _("Token is missing"), http_status_code=417)
        return

    token = frappe.cache().get_value("{0}:{1}".format(provider, state["token"]), expires=True)
    if not token:
        frappe.respond_as_web_page(_("Invalid Request"), _("Invalid Token"), http_status_code=417)
        return

    user = data["email"]

    if not user:
        frappe.respond_as_web_page(_("Invalid Request"), _("Please ensure that your profile has an email address"))
        return

    try:
        if update_oauth_user(user, data, provider) is False:
            return

    except SignupDisabledError:
        return frappe.respond_as_web_page(
            "Signup is Disabled", "Sorry. Signup from Website is disabled.", success=False, http_status_code=403
        )

    frappe.local.login_manager.user = user
    frappe.local.login_manager.post_login()

    # because of a GET request!
    frappe.db.commit()

    if frappe.utils.cint(generate_login_token):
        login_token = frappe.generate_hash(length=32)
        frappe.cache().set_value("login_token:{0}".format(login_token), frappe.local.session.sid, expires_in_sec=120)

        frappe.response["login_token"] = login_token

    else:
        redirect_post_login(desk_user=frappe.local.response.get("message") == "Logged In")
コード例 #14
0
ファイル: error.py プロジェクト: vzool/frappe
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))
コード例 #15
0
ファイル: password.py プロジェクト: Dattatech/frappetest
def update_password(user, pwd, doctype='User', fieldname='password'):
	salt = frappe.generate_hash()

	frappe.db.sql("""insert into __Auth (doctype, name, fieldname, `password`, salt, encrypted)
		values (%(doctype)s, %(name)s, %(fieldname)s, password(concat(%(pwd)s, %(salt)s)), %(salt)s, 0)
		on duplicate key update
			`password`=password(concat(%(pwd)s, %(salt)s)), salt=%(salt)s, encrypted=0""",
		{ 'doctype': doctype, 'name': user, 'fieldname': fieldname, 'pwd': pwd, 'salt': salt })
コード例 #16
0
ファイル: oauth.py プロジェクト: JiShangShiDai/frappe
def update_oauth_user(user, data, provider):
	if isinstance(data.get("location"), dict):
		data["location"] = data.get("location").get("name")

	save = False

	if not frappe.db.exists("User", user):

		# is signup disabled?
		if frappe.utils.cint(frappe.db.get_single_value("Website Settings", "disable_signup")):
			raise SignupDisabledError

		save = True
		user = frappe.new_doc("User")
		user.update({
			"doctype":"User",
			"first_name": get_first_name(data),
			"last_name": get_last_name(data),
			"email": data["email"],
			"gender": (data.get("gender") or "").title(),
			"enabled": 1,
			"new_password": frappe.generate_hash(data["email"]),
			"location": data.get("location"),
			"user_type": "Website User",
			"user_image": data.get("picture") or data.get("avatar_url")
		})

	else:
		user = frappe.get_doc("User", user)
		if not user.enabled:
			frappe.respond_as_web_page(_('Not Allowed'), _('User {0} is disabled').format(user.email))
			return False

	if provider=="facebook" and not user.get("fb_userid"):
		save = True
		user.update({
			"fb_username": data.get("username"),
			"fb_userid": data["id"],
			"user_image": "https://graph.facebook.com/{id}/picture".format(id=data["id"])
		})

	elif provider=="google" and not user.get("google_userid"):
		save = True
		user.google_userid = data["id"]

	elif provider=="github" and not user.get("github_userid"):
		save = True
		user.github_userid = data["id"]
		user.github_username = data["login"]

	elif provider=="frappe" and not user.get("frappe_userid"):
		save = True
		user.frappe_userid = data["sub"]

	if save:
		user.flags.ignore_permissions = True
		user.flags.no_welcome_mail = True
		user.save()
コード例 #17
0
ファイル: user.py プロジェクト: robulik/frappe
def generate_keys(user):
	"""
	generate api key and api secret

	:param user: str
	"""
	if "System Manager" in frappe.get_roles():
		user_details = frappe.get_doc("User", user)
		api_secret = frappe.generate_hash(length=15)
		# if api key is not set generate api key
		if not user_details.api_key:
			api_key = frappe.generate_hash(length=15)
			user_details.api_key = api_key
		user_details.api_secret = api_secret
		user_details.save()

		return {"api_secret": api_secret}
	frappe.throw(frappe._("Not Permitted"), frappe.PermissionError)
コード例 #18
0
ファイル: print_format.py プロジェクト: vhrspvl/vhrs-frappe
def read_multi_pdf(output):
	# Get the content of the merged pdf files
	fname = os.path.join("/tmp", "frappe-pdf-{0}.pdf".format(frappe.generate_hash()))
	output.write(open(fname,"wb"))

	with open(fname, "rb") as fileobj:
		filedata = fileobj.read()

	return filedata
コード例 #19
0
ファイル: file.py プロジェクト: katkamrachana/frappe
	def autoname(self):
		"""Set name for folder"""
		if self.is_folder:
			if self.folder:
				self.name = self.get_name_based_on_parent_folder()
			else:
				# home
				self.name = self.file_name
		else:
			self.name = frappe.generate_hash("", 10)
コード例 #20
0
ファイル: sessions.py プロジェクト: vrms/frappe
def generate_csrf_token():
	frappe.local.session.data.csrf_token = frappe.generate_hash()
	frappe.local.session_obj.update(force=True)

	# send sid and csrf token to the user
	# handles the case when a user logs in again from another tab
	# and it leads to invalid request in the current tab
	frappe.publish_realtime(event="csrf_generated",
		message={"sid": frappe.local.session.sid, "csrf_token": frappe.local.session.data.csrf_token},
		user=frappe.session.user)
コード例 #21
0
ファイル: twofactor.py プロジェクト: JiShangShiDai/frappe
def get_link_for_qrcode(user, totp_uri):
	'''Get link to temporary page showing QRCode.'''
	key = frappe.generate_hash(length=20)
	key_user = "{}_user".format(key)
	key_uri = "{}_uri".format(key)
	lifespan = int(frappe.db.get_value('System Settings', 'System Settings', 'lifespan_qrcode_image'))
	if lifespan<=0:
		lifespan = 240
	frappe.cache().set_value(key_uri, totp_uri, expires_in_sec=lifespan)
	frappe.cache().set_value(key_user, user, expires_in_sec=lifespan)
	return get_url('/qrcode?k={}'.format(key))
コード例 #22
0
ファイル: __init__.py プロジェクト: ESS-LLP/frappe
def token():
    dtoken             = frappe.new_doc('Chat Token')

    dtoken.token       = frappe.generate_hash()
    dtoken.ip_address  = frappe.local.request_ip
    country            = get_geo_ip_country(dtoken.ip_address)
    if country:
        dtoken.country = country['iso_code']
    dtoken.save(ignore_permissions = True)

    return dtoken.token
コード例 #23
0
def execute():
	doctypes_to_skip = []
	for doctype in ['Appraisal', 'Leave Allocation', 'Expense Claim', 'Instructor', 'Salary Slip',
					'Attendance', 'Training Feedback', 'Training Result Employee',
					'Leave Application', 'Employee Advance', 'Activity Cost', 'Training Event Employee',
					'Timesheet', 'Sales Person', 'Payroll Employee Detail']:
		if frappe.db.exists('Custom Field', { 'dt': doctype, 'fieldname': 'department'}): continue
		doctypes_to_skip.append(doctype)

	frappe.reload_doctype('User Permission')

	user_permissions = frappe.get_all("User Permission",
		filters=[['allow', '=', 'Department'], ['applicable_for', 'in', [None] + doctypes_to_skip]],
		fields=['name', 'applicable_for'])

	user_permissions_to_delete = []
	new_user_permissions_list = []

	for user_permission in user_permissions:
		if user_permission.applicable_for:
			# simply delete user permission record since it needs to be skipped.
			user_permissions_to_delete.append(user_permission.name)
		else:
			# if applicable_for is `None` it means that user permission is applicable for every doctype
			# to avoid this we need to create other user permission records and only skip the listed doctypes in this patch
			linked_doctypes = get_linked_doctypes(user_permission.allow, True).keys()
			applicable_for_doctypes = list(set(linked_doctypes) - set(doctypes_to_skip))

			user_permissions_to_delete.append(user_permission.name)

			for doctype in applicable_for_doctypes:
				if doctype:
					# Maintain sequence (name, user, allow, for_value, applicable_for, apply_to_all_doctypes)
					new_user_permissions_list.append((
						frappe.generate_hash("", 10),
						user_permission.user,
						user_permission.allow,
						user_permission.for_value,
						doctype,
						0
					))

	if new_user_permissions_list:
		frappe.db.sql('''
			INSERT INTO `tabUser Permission`
			(`name`, `user`, `allow`, `for_value`, `applicable_for`, `apply_to_all_doctypes`)
			VALUES {}'''.format(', '.join(['%s'] * len(new_user_permissions_list))), # nosec
			tuple(new_user_permissions_list)
		)

	if user_permissions_to_delete:
		frappe.db.sql('DELETE FROM `tabUser Permission` WHERE `name` IN ({})'.format( # nosec
			','.join(['%s'] * len(user_permissions_to_delete))
		), tuple(user_permissions_to_delete))
コード例 #24
0
def get_name_from_hash():
	"""
	Get a name for a Batch by generating a unique hash.
	:return: The hash that was generated.
	"""
	temp = None
	while not temp:
		temp = frappe.generate_hash()[:7].upper()
		if frappe.db.exists('Batch', temp):
			temp = None

	return temp
コード例 #25
0
ファイル: twofactor.py プロジェクト: JiShangShiDai/frappe
def authenticate_for_2factor(user):
	'''Authenticate two factor for enabled user before login.'''
	if frappe.form_dict.get('otp'):
		return
	otp_secret = get_otpsecret_for_(user)
	token = int(pyotp.TOTP(otp_secret).now())
	tmp_id = frappe.generate_hash(length=8)
	cache_2fa_data(user, token, otp_secret, tmp_id)
	verification_obj = get_verification_obj(user, token, otp_secret)
	# Save data in local
	frappe.local.response['verification'] = verification_obj
	frappe.local.response['tmp_id'] = tmp_id
コード例 #26
0
ファイル: naming.py プロジェクト: AhmedHamedTN/frappe
def make_autoname(key='', doctype='', doc=''):
	"""
   Creates an autoname from the given key:

   **Autoname rules:**

         * The key is separated by '.'
         * '####' represents a series. The string before this part becomes the prefix:
            Example: ABC.#### creates a series ABC0001, ABC0002 etc
         * 'MM' represents the current month
         * 'YY' and 'YYYY' represent the current year


   *Example:*

         * DE/./.YY./.MM./.##### will create a series like
           DE/09/01/0001 where 09 is the year, 01 is the month and 0001 is the series
	"""
	if key=="hash":
		return frappe.generate_hash(doctype, 10)

	if not "#" in key:
		key = key + ".#####"
	elif not "." in key:
		frappe.throw(_("Invalid naming series (. missing)") + (_(" for {0}").format(doctype) if doctype else ""))

	n = ''
	l = key.split('.')
	series_set = False
	today = now_datetime()

	for e in l:
		part = ''
		if e.startswith('#'):
			if not series_set:
				digits = len(e)
				part = getseries(n, digits, doctype)
				series_set = True
		elif e=='YY':
			part = today.strftime('%y')
		elif e=='MM':
			part = today.strftime('%m')
		elif e=='DD':
			part = today.strftime("%d")
		elif e=='YYYY':
			part = today.strftime('%Y')
		elif doc and doc.get(e):
			part = doc.get(e)
		else: part = e

		if isinstance(part, basestring):
			n+=part
	return n
コード例 #27
0
def get_random_group():
	doc = frappe.get_doc({
		"doctype": "Student Group",
		"student_group_name": "_Test Student Group-" + frappe.generate_hash(length=5),
		"group_based_on": "Activity"
	}).insert()

	student_list = frappe.get_all('Student', limit=5)

	doc.extend("students", [{"student":d.name, "active": 1} for d in student_list])
	doc.save()

	return doc
コード例 #28
0
ファイル: twofactor.py プロジェクト: JiShangShiDai/frappe
def qrcode_as_png(user, totp_uri):
	'''Save temporary Qrcode to server.'''
	from frappe.utils.file_manager import save_file
	folder = create_barcode_folder()
	png_file_name = '{}.png'.format(frappe.generate_hash(length=20))
	file_obj = save_file(png_file_name, png_file_name, 'User', user, folder=folder)
	frappe.db.commit()
	file_url = get_url(file_obj.file_url)
	file_path = os.path.join(frappe.get_site_path('public', 'files'), file_obj.file_name)
	url = qrcreate(totp_uri)
	with open(file_path, 'w') as png_file:
		url.png(png_file, scale=8, module_color=[0, 0, 0, 180], background=[0xff, 0xff, 0xcc])
	return file_url
コード例 #29
0
	def validate_settings(self):
		if self.enable_sync:
			if not self.secret:
				self.set("secret", frappe.generate_hash())

			if not self.woocommerce_server_url:
				frappe.throw(_("Please enter Woocommerce Server URL"))

			if not self.api_consumer_key:
				frappe.throw(_("Please enter API Consumer Key"))

			if not self.api_consumer_secret:
				frappe.throw(_("Please enter API Consumer Secret"))
コード例 #30
0
ファイル: pdf.py プロジェクト: vzool/frappe
def get_pdf(html, options=None):
    if not options:
        options = {}

    options.update({
        "print-media-type": None,
        "background": None,
        "images": None,
        'margin-top': '15mm',
        'margin-right': '15mm',
        'margin-bottom': '15mm',
        'margin-left': '15mm',
        'encoding': "UTF-8",
        'quiet': None,
        'no-outline': None,
    })

    if frappe.session and frappe.session.sid:
        options['cookie'] = [('sid', '{0}'.format(frappe.session.sid))]

    if not options.get("page-size"):
        options['page-size'] = frappe.db.get_single_value(
            "Print Settings", "pdf_page_size") or "A4"

    html = scrub_urls(html)
    fname = os.path.join("/tmp", frappe.generate_hash() + ".pdf")

    try:
        pdfkit.from_string(
            html,
            fname,
            options=options or {},
        )

        with open(fname, "rb") as fileobj:
            filedata = fileobj.read()

    except IOError, e:
        if "ContentNotFoundError" in e.message or "ContentOperationNotPermittedError" in e.message:
            # allow pdfs with missing images if file got created
            if os.path.exists(fname):
                with open(fname, "rb") as fileobj:
                    filedata = fileobj.read()

            else:
                frappe.throw(
                    _("PDF generation failed because of broken image links"))
        else:
            raise