示例#1
0
def validate_print_permission(doc):
    if frappe.form_dict.get("key"):
        if frappe.form_dict.key == doc.get_signature():
            return

    for ptype in ("read", "print"):
        if (not frappe.has_permission(doc.doctype, ptype, doc) and
                not frappe.has_website_permission(doc.doctype, ptype, doc)):
            raise frappe.PermissionError(_("No {0} permission").format(ptype))
示例#2
0
def is_whitelisted(method):
	# check if whitelisted
	if frappe.session['user'] == 'Guest':
		if (method not in frappe.guest_methods):
			frappe.msgprint(_("Not permitted"))
			raise frappe.PermissionError('Not Allowed, {0}'.format(method))

		if method not in frappe.xss_safe_methods:
			# strictly sanitize form_dict
			# escapes html characters like <> except for predefined tags like a, b, ul etc.
			for key, value in frappe.form_dict.items():
				if isinstance(value, string_types):
					frappe.form_dict[key] = frappe.utils.sanitize_html(value)

	else:
		if not method in frappe.whitelisted:
			frappe.msgprint(_("Not permitted"))
			raise frappe.PermissionError('Not Allowed, {0}'.format(method))
示例#3
0
def make(doctype=None, name=None, content=None, subject=None, sent_or_received = "Sent",
	sender=None, recipients=None, communication_medium="Email", send_email=False,
	print_html=None, print_format=None, attachments='[]', ignore_doctype_permissions=False,
	send_me_a_copy=False, cc=None):
	"""Make a new communication.

	:param doctype: Reference DocType.
	:param name: Reference Document name.
	:param content: Communication body.
	:param subject: Communication subject.
	:param sent_or_received: Sent or Received (default **Sent**).
	:param sender: Communcation sender (default current user).
	:param recipients: Communication recipients as list.
	:param communication_medium: Medium of communication (default **Email**).
	:param send_mail: Send via email (default **False**).
	:param print_html: HTML Print format to be sent as attachment.
	:param print_format: Print Format name of parent document to be sent as attachment.
	:param attachments: List of attachments as list of files or JSON string.
	:param send_me_a_copy: Send a copy to the sender (default **False**).
	"""

	is_error_report = (doctype=="User" and name==frappe.session.user and subject=="Error Report")

	if doctype and name and not is_error_report and not frappe.has_permission(doctype, "email", name) and not ignore_doctype_permissions:
		raise frappe.PermissionError("You are not allowed to send emails related to: {doctype} {name}".format(
			doctype=doctype, name=name))

	if not sender:
		sender = get_formatted_email(frappe.session.user)

	comm = frappe.get_doc({
		"doctype":"Communication",
		"subject": subject,
		"content": content,
		"sender": sender,
		"recipients": recipients,
		"cc": cc or None,
		"communication_medium": communication_medium,
		"sent_or_received": sent_or_received,
		"reference_doctype": doctype,
		"reference_name": name
	})
	comm.insert(ignore_permissions=True)

	# needed for communication.notify which uses celery delay
	# if not committed, delayed task doesn't find the communication
	frappe.db.commit()

	if send_email:
		comm.send_me_a_copy = send_me_a_copy
		comm.send(print_html, print_format, attachments, send_me_a_copy=send_me_a_copy)

	return {
		"name": comm.name,
		"emails_not_sent_to": ", ".join(comm.emails_not_sent_to) if hasattr(comm, "emails_not_sent_to") else None
	}
示例#4
0
    def append_table(self, table_name):
        self.tables.append(table_name)
        doctype = table_name[4:-1]
        ptype = 'select' if frappe.only_has_select_perm(doctype) else 'read'

        if (not self.flags.ignore_permissions) and\
          (not frappe.has_permission(doctype, ptype=ptype)):
            frappe.flags.error_message = _(
                'Insufficient Permission for {0}').format(frappe.bold(doctype))
            raise frappe.PermissionError(doctype)
示例#5
0
def execute_cmd(cmd):
    """execute a request as python module"""
    method = get_attr(cmd)

    # check if whitelisted
    if frappe.session['user'] == 'Guest':
        if (method not in frappe.guest_methods):
            frappe.msgprint(_("Not permitted"))
            raise frappe.PermissionError('Not Allowed, %s' % str(method))
    else:
        if not method in frappe.whitelisted:
            frappe.msgprint(_("Not permitted"))
            raise frappe.PermissionError('Not Allowed, %s' % str(method))

    ret = frappe.call(method, **frappe.form_dict)

    # returns with a message
    if ret:
        frappe.response['message'] = ret
示例#6
0
def can_export(doctype, raise_exception=False):
    if not ("System Manager" in frappe.get_roles()
            or has_permission(doctype, "export")):
        if raise_exception:
            raise frappe.PermissionError(
                "You are not allowed to export: {doctype}".format(
                    doctype=doctype))
        else:
            return False
    return True
示例#7
0
def can_export(doctype, raise_exception=False):
	if "System Manager" in frappe.get_roles():
		return True
	else:
		role_permissions = frappe.permissions.get_role_permissions(doctype)
		has_access = role_permissions.get('export') or \
			role_permissions.get('if_owner').get('export')
		if not has_access and raise_exception:
			raise frappe.PermissionError(_("You are not allowed to export {} doctype").format(doctype))
		return has_access
示例#8
0
def get_context(context):
    if frappe.session.user == 'Guest':
        frappe.local.flags.redirect_location = "/login?" + urlencode(
            {"redirect-to": frappe.local.request.full_path})
        raise frappe.Redirect

    app = frappe.form_dict.app
    if not app:
        raise frappe.DoesNotExistError(_("Application not specified"))

    device_link = frappe.form_dict.device
    app_inst = frappe.form_dict.app_inst
    version_want = frappe.form_dict.version
    if device_link and (not app_inst or not version_want):
        frappe.local.flags.redirect_location = "/app_editor?" + urlencode(
            {"app": app})
        raise frappe.Redirect

    app_doc = frappe.get_doc("IOT Application", app)
    user_roles = frappe.get_roles(frappe.session.user)
    if 'App User' not in user_roles:
        raise frappe.PermissionError

    if frappe.session.user != 'Administrator' and app_doc.owner != frappe.session.user:
        raise frappe.PermissionError(
            _("You are not the owner of application {0}").format(
                app_doc.app_name))

    context.no_cache = 1

    context.doc = app_doc
    context.device_link = device_link
    context.app_inst = app_inst
    context.releases = frappe.db.get_all("IOT Application Version",
                                         fields="*",
                                         filters={"app": app},
                                         limit=10,
                                         order_by="version desc")

    version_editor = editor_worksapce_version(app) or -1
    context.version_editor = version_editor

    if version_want is not None:
        version_want = int(version_want)
        context.version_want = version_want

        if version_editor == -1:
            version_editor = version_want
            from app_center.editor import editor_revert
            editor_revert(app, version_editor)
            context.version_editor = version_editor

        if version_editor != version_want:
            context.show_version_warning = True
示例#9
0
def add(user, defkey, defvalue):
	if not frappe.permissions.can_restrict_user(user, defkey, defvalue):
		raise frappe.PermissionError("Cannot Restrict User: {user} for DocType: {doctype} and Name: {name}".format(
			user=user, doctype=defkey, name=defvalue))

	# check if already exists
	d = frappe.db.sql("""select name from tabDefaultValue
		where parent=%s and parenttype='Restriction' and defkey=%s and defvalue=%s""", (user, defkey, defvalue))

	if not d:
		frappe.defaults.add_default(defkey, defvalue, user, "Restriction")
示例#10
0
def make(doctype=None, name=None, content=None, subject=None, sent_or_received = "Sent",
	sender=None, recipients=None, communication_medium="Email", send_email=False, 
	print_html=None, attachments='[]', send_me_a_copy=False, set_lead=True, date=None):
	
	if doctype and name and not frappe.has_permission(doctype, "email", name):
		raise frappe.PermissionError("You are not allowed to send emails related to: {doctype} {name}".format(
			doctype=doctype, name=name))
			
	_make(doctype=doctype, name=name, content=content, subject=subject, sent_or_received=sent_or_received,
		sender=sender, recipients=recipients, communication_medium=communication_medium, send_email=send_email, 
		print_html=print_html, attachments=attachments, send_me_a_copy=send_me_a_copy, set_lead=set_lead, 
		date=date)
def confirm_device_otp_token():
    email = frappe.form_dict.get('email')
    tmp_id = frappe.form_dict.get('tmp_id')
    otp = frappe.form_dict.get('otp')

    if email and not frappe.db.exists('User', email):
        raise frappe.PermissionError("User does not exist")

    if not otp:
        raise frappe.PermissionError("OTP not found")

    if not tmp_id:
        raise frappe.PermissionError("ID not found")

    hotp_token = frappe.cache().get(tmp_id + '_token')
    otp_secret = frappe.cache().get(tmp_id + '_otp_secret')

    if not otp_secret:
        raise frappe.PermissionError("Login expired")

    hotp = pyotp.HOTP(otp_secret)
    if hotp_token:
        if hotp.verify(otp, int(hotp_token)):
            frappe.cache().delete(tmp_id + '_token')
            key = _generate_key(email)
            return key
        else:
            raise frappe.PermissionError("OTP does not match")

    totp = pyotp.TOTP(otp_secret)
    if totp.verify(otp):
        key = _generate_key(email)
        return key
    else:
        raise frappe.PermissionError("OTP does not match")
示例#12
0
	def run_report(self, data, docdata=None):
		doctype = data.get('doctype')
		rdoc = frappe.get_doc(doctype, data.get('report_name'))

		#call hook before run the report
		utils.call_hook_for_param(rdoc, "jasper_before_run_report", data)

		rtype = rdoc.get("jasper_report_type")
		if data.get("fortype").lower() == "doctype" and rtype in ("List", "Form"):
			for docname in data.get('name_ids', []) or []:
				if not utils.check_frappe_permission(rdoc.jasper_doctype, docname, ptypes=("read", "print")):
					raise frappe.PermissionError(_("No {0} permission for document {1} in doctype {3}.").format("read or print", docname, rdoc.jasper_doctype))
			#if user can read doc it is possible that can't print it! Just uncheck Read permission in doctype Jasper Reports
		if not utils.check_frappe_permission("Jasper Reports", data.get('report_name', ""), ptypes="read"):
			raise frappe.PermissionError(_("You don't have print permission."))

		params = rdoc.jasper_parameters
		origin = rdoc.jasper_report_origin.lower()
		pformat = data.get('pformat')
		ncopies = get_copies(rdoc, pformat)
		if origin == "localserver":
			path = rdoc.jrxml_root_path
			self.get_server("local")
			if not path:
				frappe.throw(_("%s: Import first a jrxml file." % rdoc.name))
			for_all_sites = rdoc.jasper_all_sites_report
			result = self.jpl.run_local_report_async(path, rdoc, data=data, params=params, pformat=pformat, ncopies=ncopies, for_all_sites=for_all_sites)
		else:
			path = rdoc.jasper_report_path
			self.get_server("server")
			if not self.jps.is_login:
				frappe.msgprint(_("Jasper Server, login error."))
				return

			result = self.jps.run_remote_report_async(path, rdoc, data=data, params=params, pformat=pformat, ncopies=ncopies)

		return result
示例#13
0
def execute_cmd(cmd):
	"""execute a request as python module"""
	for hook in frappe.get_hooks("override_whitelisted_methods", {}).get(cmd, []):
		# override using the first hook
		cmd = hook
		break

	method = get_attr(cmd)

	# check if whitelisted
	if frappe.session['user'] == 'Guest':
		if (method not in frappe.guest_methods):
			frappe.msgprint(_("Not permitted"))
			raise frappe.PermissionError('Not Allowed, %s' % str(method))
	else:
		if not method in frappe.whitelisted:
			frappe.msgprint(_("Not permitted"))
			raise frappe.PermissionError('Not Allowed, %s' % str(method))

	ret = frappe.call(method, **frappe.form_dict)

	# returns with a message
	if ret:
		frappe.response['message'] = ret
示例#14
0
def get(name):
	"""
	   Return the :term:`doclist` of the `Page` specified by `name`
	"""
	page = frappe.get_doc('Page', name)
	if page.is_permitted():
		page.load_assets()
		docs = frappe._dict(page.as_dict())
		if getattr(page, '_dynamic_page', None):
			docs['_dynamic_page'] = 1

		return docs
	else:
		frappe.response['403'] = 1
		raise frappe.PermissionError('No read permission for Page %s' %(page.title or name))
示例#15
0
def get_context(context):
	if frappe.session.user == 'Guest':
		frappe.local.flags.redirect_location = "/login?" + urlencode({"redirect-to": frappe.local.request.full_path})
		raise frappe.Redirect

	context.no_cache = 1

	name = frappe.form_dict.name
	if not name:
		raise frappe.PermissionError(_("Application issue is missing!"))

	doc = frappe.get_doc('IOT Application Issue', name)

	context.doc = frappe.get_doc('IOT Application', doc.app)
	context.issue = doc
	context.has_release = frappe.get_value("IOT Application Version", {"app": doc.app})
示例#16
0
文件: db_query.py 项目: vrms/frappe
def get_list(doctype, *args, **kwargs):
	'''wrapper for DatabaseQuery'''
	kwargs.pop('cmd', None)
	kwargs.pop('ignore_permissions', None)

	# If doctype is child table
	if frappe.is_table(doctype):
		# Example frappe.db.get_list('Purchase Receipt Item', {'parent': 'Purchase Receipt'})
		# Here purchase receipt is the parent doctype of the child doctype Purchase Receipt Item

		if not kwargs.get('parent'):
			frappe.flags.error_message = _('Parent is required to get child table data')
			raise frappe.PermissionError(doctype)

		check_parent_permission(kwargs.get('parent'), doctype)
		del kwargs['parent']

	return DatabaseQuery(doctype).execute(None, *args, **kwargs)
def initiate_pwd_reset():
    email = frappe.form_dict.get('email')
    if email and frappe.db.exists('User', email):
        authenticate_for_2factor(email)
        phone = get_phone_no(email)
        if phone:
            tmp_id = frappe.local.response['tmp_id']
            otp_secret = frappe.cache().get(tmp_id + '_otp_secret')
            token = frappe.cache().get(tmp_id + '_token')
            # Surprisingly following 2FA method is not working
            # status = send_token_via_sms(otp_secret, token=token, phone_no=phone)
            from frappe.core.doctype.sms_settings.sms_settings import send_sms
            hotp = pyotp.HOTP(otp_secret)
            msg = 'Your verification code is {}'.format(hotp.at(int(token)))
            send_sms([cstr(phone)], msg)
        frappe.db.commit()
    else:
        raise frappe.PermissionError("User does not exist")
示例#18
0
def make(doctype=None, name=None, content=None, subject=None, sent_or_received = "Sent",
	sender=None, recipients=None, communication_medium="Email", send_email=False,
	print_html=None, print_format=None, attachments='[]', ignore_doctype_permissions=False):
	"""Make a new communication.

	:param doctype: Reference DocType.
	:param name: Reference Document name.
	:param content: Communication body.
	:param subject: Communication subject.
	:param sent_or_received: Sent or Received (default **Sent**).
	:param sender: Communcation sender (default current user).
	:param recipients: Communication recipients as list.
	:param communication_medium: Medium of communication (default **Email**).
	:param send_mail: Send via email (default **False**).
	:param print_html: HTML Print format to be sent as attachment.
	:param print_format: Print Format name of parent document to be sent as attachment.
	:param attachments: List of attachments as list of files or JSON string."""

	is_error_report = (doctype=="User" and name==frappe.session.user and subject=="Error Report")

	if doctype and name and not is_error_report and not frappe.has_permission(doctype, "email", name) and not ignore_doctype_permissions:
		raise frappe.PermissionError("You are not allowed to send emails related to: {doctype} {name}".format(
			doctype=doctype, name=name))

	if not sender and frappe.session.user != "Administrator":
		sender = get_formatted_email(frappe.session.user)

	comm = frappe.get_doc({
		"doctype":"Communication",
		"subject": subject,
		"content": content,
		"sender": sender,
		"recipients": recipients,
		"communication_medium": "Email",
		"sent_or_received": sent_or_received,
		"reference_doctype": doctype,
		"reference_name": name
	})
	comm.insert(ignore_permissions=True)

	if send_email:
		comm.send(print_html, print_format, attachments)

	return comm.name
示例#19
0
文件: load.py 项目: moh5q/erpnext
def getdoc(doctype, name, user=None):
    """
	Loads a doclist for a given document. This method is called directly from the client.
	Requries "doctype", "name" as form variables.
	Will also call the "onload" method on the document.
	"""

    if not (doctype and name):
        raise Exception('doctype and name required!')

    if not name:
        name = doctype

    if not frappe.db.exists(doctype, name):
        return []

    try:
        doc = frappe.get_doc(doctype, name)
        run_onload(doc)

        if not doc.has_permission("read"):
            frappe.flags.error_message = _(
                'Insufficient Permission for {0}').format(
                    frappe.bold(doctype + ' ' + name))
            raise frappe.PermissionError(("read", doctype, name))

        doc.apply_fieldlevel_read_permissions()

        # add file list
        doc.add_viewed()
        get_docinfo(doc)

    except Exception:
        frappe.errprint(frappe.utils.get_traceback())
        raise

    if doc and not name.startswith('_'):
        frappe.get_user().update_recent(doctype, name)

    doc.add_seen()

    frappe.response.docs.append(doc)
示例#20
0
def delete_multiple(web_form_name, docnames):
	web_form = frappe.get_doc("Web Form", web_form_name)

	docnames = json.loads(docnames)

	allowed_docnames = []
	restricted_docnames = []

	for docname in docnames:
		owner = frappe.db.get_value(web_form.doc_type, docname, "owner")
		if frappe.session.user == owner and web_form.allow_delete:
			allowed_docnames.append(docname)
		else:
			restricted_docnames.append(docname)

	for docname in allowed_docnames:
		frappe.delete_doc(web_form.doc_type, docname, ignore_permissions=True)

	if restricted_docnames:
		raise frappe.PermissionError("You do not have permisssion to delete " + ", ".join(restricted_docnames))
示例#21
0
def make_file_document(
        file_key, doctype=None, docname=None, fieldname=None, is_private=None,
        ignore_permissions=False):
    user = None
    if not ignore_permissions and frappe.session.user == 'Guest':
        if frappe.get_system_settings('allow_guests_to_upload_files'):
            ignore_permissions = True
        else:
            raise frappe.PermissionError("Guest uploads are not allowed")
    else:
        user = frappe.get_doc("User", frappe.session.user)

    files = frappe.request.files
    content = None
    filename = None

    if file_key in files:
        file = files[file_key]
        content = file.stream.read()
        filename = file.filename

    frappe.local.uploaded_file = content
    frappe.local.uploaded_filename = filename

    if frappe.session.user == 'Guest' or (user and not user.has_desk_access()):
        import mimetypes
        filetype = mimetypes.guess_type(filename)[0]
        if filetype not in ALLOWED_MIMETYPES:
            frappe.throw(frappe._("You can only upload JPG, PNG, PDF, or Microsoft documents."))

    ret = frappe.get_doc({
        "doctype": "File",
        "attached_to_doctype": doctype,
        "attached_to_name": docname,
        "attached_to_field": fieldname,
        "file_name": filename,
        "is_private": cint(is_private),
        "content": content
    })
    ret.save(ignore_permissions=ignore_permissions)
    return ret
示例#22
0
def get_context(context):
    if frappe.session.user != 'Guest':
        frappe.local.flags.redirect_location = frappe.form_dict.redirect or "/me"
        raise frappe.Redirect

    app = frappe.form_dict.app
    openid = frappe.form_dict.openid
    redirect = frappe.form_dict.redirect

    if not (app and openid):
        raise frappe.PermissionError("App or Openid does not exists!")

    context.no_cache = 1
    context.show_sidebar = False

    context.title = _("Binding Wechat")
    context.doc = {
        "app": app,
        "openid": openid,
        "redirect": redirect,
    }
示例#23
0
def get_context(context):
    if frappe.session.user == 'Guest':
        frappe.local.flags.redirect_location = "/login?" + urlencode(
            {"redirect-to": frappe.local.request.full_path})
        raise frappe.Redirect

    app = frappe.form_dict.app
    if not app:
        raise frappe.DoesNotExistError(_("Application not specified"))

    app_doc = frappe.get_doc("IOT Application", app)
    user_roles = frappe.get_roles(frappe.session.user)
    if 'App User' not in user_roles:
        raise frappe.PermissionError

    if frappe.session.user != 'Administrator' and app_doc.owner != frappe.session.user:
        raise frappe.PermissionError(
            _("You are not the owner of application {0}").format(
                app_doc.app_name))

    context.no_cache = 1

    context.doc = app_doc
示例#24
0
def get_context(context):
    from cloud.cloud.doctype.cloud_company.cloud_company import list_user_companies
    from cloud.cloud.doctype.cloud_company_group.cloud_company_group import list_user_groups

    if frappe.session.user == 'Guest':
        frappe.local.flags.redirect_location = "/login"
        raise frappe.Redirect

    user_roles = frappe.get_roles(frappe.session.user)
    if 'IOT User' not in user_roles:
        raise frappe.PermissionError(
            "Your account is not an IOT User! Please concat admin for user permission request!"
        )

    context.no_cache = 1
    context.show_sidebar = True

    # context.parents = [{"title": _("Back"), "route": frappe.get_request_header("referer")}]

    context.doc = {
        "companies": list_user_companies(frappe.session.user),
        "groups": list_user_groups(frappe.session.user),
        "devices": get_user_devices(frappe.session.user)
    }
示例#25
0
 def raise_no_permission_to(self, perm_type):
     """Raise `frappe.PermissionError`."""
     msg = _("No permission to {0} {1} {2}".format(perm_type, self.doctype,
                                                   self.name or ""))
     frappe.msgprint(msg)
     raise frappe.PermissionError(msg)
示例#26
0
def make(doctype=None,
         name=None,
         content=None,
         subject=None,
         sent_or_received="Sent",
         sender=None,
         sender_full_name=None,
         recipients=None,
         communication_medium="Email",
         send_email=False,
         print_html=None,
         print_format=None,
         attachments='[]',
         send_me_a_copy=False,
         cc=None,
         bcc=None,
         flags=None,
         read_receipt=None,
         print_letterhead=True):
    """Make a new communication.

	:param doctype: Reference DocType.
	:param name: Reference Document name.
	:param content: Communication body.
	:param subject: Communication subject.
	:param sent_or_received: Sent or Received (default **Sent**).
	:param sender: Communcation sender (default current user).
	:param recipients: Communication recipients as list.
	:param communication_medium: Medium of communication (default **Email**).
	:param send_email: Send via email (default **False**).
	:param print_html: HTML Print format to be sent as attachment.
	:param print_format: Print Format name of parent document to be sent as attachment.
	:param attachments: List of attachments as list of files or JSON string.
	:param send_me_a_copy: Send a copy to the sender (default **False**).
	"""

    is_error_report = (doctype == "User" and name == frappe.session.user
                       and subject == "Error Report")
    send_me_a_copy = cint(send_me_a_copy)

    if doctype and name and not is_error_report and not frappe.has_permission(
            doctype, "email",
            name) and not (flags or {}).get('ignore_doctype_permissions'):
        raise frappe.PermissionError(
            "You are not allowed to send emails related to: {doctype} {name}".
            format(doctype=doctype, name=name))

    if not sender:
        sender = get_formatted_email(frappe.session.user)

    if isinstance(recipients, list):
        recipients = ', '.join(recipients)

    comm = frappe.get_doc({
        "doctype": "Communication",
        "subject": subject,
        "content": content,
        "sender": sender,
        "sender_full_name": sender_full_name,
        "recipients": recipients,
        "cc": cc or None,
        "bcc": bcc or None,
        "communication_medium": communication_medium,
        "sent_or_received": sent_or_received,
        "reference_doctype": doctype,
        "reference_name": name,
        "message_id": get_message_id().strip(" <>"),
        "read_receipt": read_receipt,
        "has_attachment": 1 if attachments else 0
    })
    comm.insert(ignore_permissions=True)

    if not doctype:
        # if no reference given, then send it against the communication
        comm.db_set(
            dict(reference_doctype='Communication', reference_name=comm.name))

    if isinstance(attachments, string_types):
        attachments = json.loads(attachments)

    # if not committed, delayed task doesn't find the communication
    if attachments:
        add_attachments(comm.name, attachments)

    frappe.db.commit()

    if cint(send_email):
        frappe.flags.print_letterhead = cint(print_letterhead)
        comm.send(print_html,
                  print_format,
                  attachments,
                  send_me_a_copy=send_me_a_copy)

    return {
        "name":
        comm.name,
        "emails_not_sent_to":
        ", ".join(comm.emails_not_sent_to)
        if hasattr(comm, "emails_not_sent_to") else None
    }
示例#27
0
def jasper_make_email(doctype=None,
                      name=None,
                      content=None,
                      subject=None,
                      sent_or_received="Sent",
                      sender=None,
                      recipients=None,
                      communication_medium="Email",
                      send_email=False,
                      print_html=None,
                      print_format=None,
                      attachments='[]',
                      send_me_a_copy=False,
                      set_lead=True,
                      date=None,
                      jasper_doc=None,
                      docdata=None):

    custom_print_html = print_html
    custom_print_format = print_format

    jasper_polling_time = frappe.db.get_value('JasperServerConfig',
                                              fieldname="jasper_polling_time")
    data = json.loads(jasper_doc)
    result = run_report(data, docdata)
    if result[0].get("status", "not ready") != "ready":
        poll_data = prepare_polling(result)
        result = report_polling(poll_data)
        limit = 0
        while limit <= 10 and result[0].get("status", "not ready") != "ready":
            time.sleep(cint(jasper_polling_time) / 1000)
            result = report_polling(poll_data)
            limit += 1

    pformat = data.get("pformat")
    #we have to remove the original and send only duplicate
    if result[0].get("status", "not ready") == "ready":
        rdoc = frappe.get_doc(data.get("doctype"), data.get('report_name'))
        ncopies = get_copies(rdoc, pformat)
        fileName, jasper_content, report_name = _get_report(result[0])
        merge_all = True
        pages = None
        if pformat == "pdf" and ncopies > 1:
            merge_all = False
            pages = get_pages(ncopies, len(jasper_content))

        sender = get_sender(sender)

        if pformat == "html":
            custom_print_html = True
            url, filepath = make_pdf(fileName,
                                     jasper_content,
                                     pformat,
                                     report_name,
                                     merge_all=merge_all,
                                     pages=pages,
                                     email=True)
            output = filepath
            file_name = output.rsplit("/", 1)
            if len(file_name) > 1:
                file_name = file_name[1]
            else:
                file_name = file_name[0]

        elif pformat == "pdf":
            custom_print_format = "pdf"
            file_name, filepath, output, url = make_pdf(
                fileName,
                jasper_content,
                pformat,
                report_name,
                reqId=result[0].get("requestId"),
                merge_all=merge_all,
                pages=pages,
                email=True)
            output = output.getvalue()

        else:
            file_name, output = make_pdf(fileName,
                                         jasper_content,
                                         pformat,
                                         report_name,
                                         merge_all=merge_all,
                                         pages=pages,
                                         email=True)
            filepath = url = get_email_other_path(data, file_name,
                                                  result[0].get("requestId"),
                                                  sender)
            output = output.getvalue()
            #remove name from filepath
            filepath = filepath.rsplit("/", 1)[0]

    else:
        frappe.throw(
            _("Error generating %s format, try again later.") % (pformat, ))
        frappe.errprint(frappe.get_traceback())
        return

    if not check_frappe_permission(
            data.get("doctype"), data.get('report_name'), ptypes=("read", )):
        raise frappe.PermissionError(
            (_("You are not allowed to send emails related to") +
             ": {doctype} {name}").format(doctype=data.get("doctype"),
                                          name=data.get('report_name')))

    jasper_run_method("jasper_before_sendmail",
                      data,
                      file_name,
                      output,
                      url,
                      doctype=doctype,
                      name=name,
                      content=content,
                      subject=subject,
                      sent_or_received=sent_or_received,
                      sender=sender,
                      recipients=recipients,
                      print_html=print_html,
                      print_format=print_format,
                      attachments=attachments,
                      send_me_a_copy=send_me_a_copy)

    version = getFrappeVersion().major
    if version >= 5:
        file_path = None

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

        if pformat != "html":
            file_path = os.path.join(filepath, file_name)
            jasper_save_email(file_path, output)
            attachments.append(file_path)

        comm_name = sendmail_v5(url,
                                doctype=doctype,
                                name=name,
                                content=content,
                                subject=subject,
                                sent_or_received=sent_or_received,
                                sender=sender,
                                recipients=recipients,
                                send_email=send_email,
                                print_html=print_html,
                                print_format=print_format,
                                attachments=attachments)

        set_jasper_email_doctype(data.get('report_name'), recipients, sender,
                                 frappe.utils.now(), url, file_name)
        jasper_run_method("jasper_after_sendmail", data, url, file_name,
                          file_path)

        return comm_name

    print_format = custom_print_format
    print_html = custom_print_html

    sendmail(file_name,
             output,
             url,
             doctype=doctype,
             name=name,
             content=content,
             subject=subject,
             sent_or_received=sent_or_received,
             sender=sender,
             recipients=recipients,
             print_html=print_html,
             print_format=print_format,
             attachments=attachments,
             send_me_a_copy=send_me_a_copy)

    file_path = None
    if pformat != "html":
        file_path = os.path.join(filepath, file_name)
        jasper_save_email(file_path, output)

    set_jasper_email_doctype(data.get('report_name'), recipients, sender,
                             frappe.utils.now(), url, file_name)
    jasper_run_method("jasper_after_sendmail", data, url, file_name, file_path)
示例#28
0
 def raise_no_permission_to(self, perm_type):
     """Raise `frappe.PermissionError`."""
     raise frappe.PermissionError("No permission to {} {} {}".format(
         perm_type, self.doctype, self.name or ""))
示例#29
0
    def execute(self,
                query=None,
                fields=None,
                filters=None,
                or_filters=None,
                docstatus=None,
                group_by=None,
                order_by=None,
                limit_start=False,
                limit_page_length=None,
                as_list=False,
                with_childnames=False,
                debug=False,
                ignore_permissions=False,
                user=None,
                with_comment_count=False,
                join='left join',
                distinct=False,
                start=None,
                page_length=None,
                limit=None,
                ignore_ifnull=False,
                save_user_settings=False,
                save_user_settings_fields=False,
                update=None,
                add_total_row=None,
                user_settings=None):
        if not ignore_permissions and not frappe.has_permission(
                self.doctype, "read", user=user):
            frappe.flags.error_message = _(
                'Insufficient Permission for {0}').format(
                    frappe.bold(self.doctype))
            raise frappe.PermissionError(self.doctype)

        # fitlers and fields swappable
        # its hard to remember what comes first
        if (isinstance(fields, dict) or (isinstance(fields, list) and fields
                                         and isinstance(fields[0], list))):
            # if fields is given as dict/list of list, its probably filters
            filters, fields = fields, filters

        elif fields and isinstance(filters, list) \
         and len(filters) > 1 and isinstance(filters[0], string_types):
            # if `filters` is a list of strings, its probably fields
            filters, fields = fields, filters

        if fields:
            self.fields = fields
        else:
            self.fields = ["`tab{0}`.`name`".format(self.doctype)]

        if start: limit_start = start
        if page_length: limit_page_length = page_length
        if limit: limit_page_length = limit

        self.filters = filters or []
        self.or_filters = or_filters or []
        self.docstatus = docstatus or []
        self.group_by = group_by
        self.order_by = order_by
        self.limit_start = 0 if (limit_start is False) else cint(limit_start)
        self.limit_page_length = cint(
            limit_page_length) if limit_page_length else None
        self.with_childnames = with_childnames
        self.debug = debug
        self.join = join
        self.distinct = distinct
        self.as_list = as_list
        self.ignore_ifnull = ignore_ifnull
        self.flags.ignore_permissions = ignore_permissions
        self.user = user or frappe.session.user
        self.update = update
        self.user_settings_fields = copy.deepcopy(self.fields)
        #self.debug = True

        if user_settings:
            self.user_settings = json.loads(user_settings)

        if query:
            result = self.run_custom_query(query)
        else:
            result = self.build_and_run()

        if with_comment_count and not as_list and self.doctype:
            self.add_comment_count(result)

        if save_user_settings:
            self.save_user_settings_fields = save_user_settings_fields
            self.update_user_settings()

        return result
 def validate(self):
     if not self.jasper_email_report_name:
         raise frappe.PermissionError(
             _("You are not allowed to add this document."))