예제 #1
0
def get_redirect_uri(doc, token, payerid):
	data = json.loads(doc.data)

	if data.get("subscription_details") or data.get("subscription_id"):
		return get_url("{0}.create_recurring_profile?token={1}&payerid={2}".format(api_path, token, payerid))
	else:
		return get_url("{0}.confirm_payment?token={1}".format(api_path, token))
예제 #2
0
    def send_email(self):
        """
			Sends the link to backup file located at epaas/backups
		"""
        from dataent.email import get_system_managers

        recipient_list = get_system_managers()
        db_backup_url = get_url(
            os.path.join('backups', os.path.basename(self.backup_path_db)))
        files_backup_url = get_url(
            os.path.join('backups', os.path.basename(self.backup_path_files)))

        msg = """Hello,

Your backups are ready to be downloaded.

1. [Click here to download the database backup](%(db_backup_url)s)
2. [Click here to download the files backup](%(files_backup_url)s)

This link will be valid for 24 hours. A new backup will be available for
download only after 24 hours.""" % {
            "db_backup_url": db_backup_url,
            "files_backup_url": files_backup_url
        }

        datetime_str = datetime.fromtimestamp(
            os.stat(self.backup_path_db).st_ctime)
        subject = datetime_str.strftime(
            "%d/%m/%Y %H:%M:%S") + """ - Backup ready to be downloaded"""

        dataent.sendmail(recipients=recipient_list, msg=msg, subject=subject)
        return recipient_list
예제 #3
0
    def test_scrub_urls(self):
        html = '''
			<p>You have a new message from: <b>John</b></p>
			<p>Hey, wassup!</p>
			<div class="more-info">
				<a href="http://test.com">Test link 1</a>
				<a href="/about">Test link 2</a>
				<a href="login">Test link 3</a>
				<img src="/assets/dataent/test.jpg">
			</div>
			<div style="background-image: url('/assets/dataent/bg.jpg')">
				Please mail us at <a href="mailto:[email protected]">email</a>
			</div>
		'''

        html = scrub_urls(html)
        url = get_url()

        self.assertTrue('<a href="http://test.com">Test link 1</a>' in html)
        self.assertTrue(
            '<a href="{0}/about">Test link 2</a>'.format(url) in html)
        self.assertTrue(
            '<a href="{0}/login">Test link 3</a>'.format(url) in html)
        self.assertTrue(
            '<img src="{0}/assets/dataent/test.jpg">'.format(url) in html)
        self.assertTrue(
            'style="background-image: url(\'{0}/assets/dataent/bg.jpg\') !important"'
            .format(url) in html)
        self.assertTrue('<a href="mailto:[email protected]">email</a>' in html)
예제 #4
0
    def send_login_mail(self, subject, template, add_args, now=None):
        """send mail with login details"""
        from dataent.utils.user import get_user_fullname
        from dataent.utils import get_url

        full_name = get_user_fullname(dataent.session['user'])
        if full_name == "Guest":
            full_name = "Administrator"

        args = {
            'first_name': self.first_name or self.last_name or "user",
            'user': self.name,
            'title': subject,
            'login_url': get_url(),
            'user_fullname': full_name
        }

        args.update(add_args)

        sender = dataent.session.user not in STANDARD_USERS and get_formatted_email(
            dataent.session.user) or None

        dataent.sendmail(
            recipients=self.email,
            sender=sender,
            subject=subject,
            template=template,
            args=args,
            header=[subject, "green"],
            delayed=(not now) if now != None else self.flags.delay_emails,
            retry=3)
예제 #5
0
def _notify(args):
    from dataent.utils import get_fullname, get_url

    args = dataent._dict(args)
    contact = args.contact
    txt = args.txt

    try:
        if not isinstance(contact, list):
            contact = [
                dataent.db.get_value("User", contact, "email") or contact
            ]

        dataent.sendmail(\
         recipients=contact,
         sender= dataent.db.get_value("User", dataent.session.user, "email"),
         subject=_("New message from {0}").format(get_fullname(dataent.session.user)),
         template="new_message",
         args={
          "from": get_fullname(dataent.session.user),
          "message": txt,
          "link": get_url()
         },
         header=[_('New Message'), 'orange'])
    except dataent.OutgoingEmailError:
        pass
예제 #6
0
    def on_payment_authorized(self, status=None):
        if not status:
            return

        shopping_cart_settings = dataent.get_doc("Shopping Cart Settings")

        if status in ["Authorized", "Completed"]:
            redirect_to = None
            self.run_method("set_as_paid")

            # if shopping cart enabled and in session
            if (shopping_cart_settings.enabled
                    and hasattr(dataent.local, "session")
                    and dataent.local.session.user != "Guest"):

                success_url = shopping_cart_settings.payment_success_url
                if success_url:
                    redirect_to = ({
                        "Orders": "/orders",
                        "Invoices": "/invoices",
                        "My Account": "/me"
                    }).get(success_url, "/me")
                else:
                    redirect_to = get_url("/orders/{0}".format(
                        self.reference_name))

            return redirect_to
예제 #7
0
파일: test_api.py 프로젝트: dataent/dataent
    def test_insert_many(self):
        if os.environ.get('CI'):
            return
        from dataent.dataentclient import DataentClient

        dataent.db.sql(
            'delete from `tabToDo` where description like "Test API%"')
        dataent.db.commit()

        server = DataentClient(get_url(),
                               "Administrator",
                               "admin",
                               verify=False)

        server.insert_many([
            {
                "doctype": "ToDo",
                "description": "Test API 1"
            },
            {
                "doctype": "ToDo",
                "description": "Test API 2"
            },
            {
                "doctype": "ToDo",
                "description": "Test API 3"
            },
        ])

        self.assertTrue(
            dataent.db.get_value('ToDo', {'description': 'Test API 1'}))
        self.assertTrue(
            dataent.db.get_value('ToDo', {'description': 'Test API 2'}))
        self.assertTrue(
            dataent.db.get_value('ToDo', {'description': 'Test API 3'}))
예제 #8
0
    def reset_password(self, send_email=False):
        from dataent.utils import random_string, get_url

        key = random_string(32)
        self.db_set("reset_password_key", key)
        link = get_url("/update-password?key=" + key)

        if send_email:
            self.password_reset_mail(link)

        return link
예제 #9
0
def get_confirm_workflow_action_url(doc, action, user):
    confirm_action_method = "/api/method/dataent.workflow.doctype.workflow_action.workflow_action.confirm_action"

    params = {
        "action": action,
        "doctype": doc.get('doctype'),
        "docname": doc.get('name'),
        "user": user
    }

    return get_url(confirm_action_method + "?" + get_signed_params(params))
예제 #10
0
파일: importer.py 프로젝트: dataent/dataent
    def is_valid_url(url):
        is_valid = False
        if url.startswith("/files") or url.startswith("/private/files"):
            url = get_url(url)

        try:
            r = requests.get(url)
            is_valid = True if r.status_code == 200 else False
        except Exception:
            pass

        return is_valid
예제 #11
0
def get_workflow_action_url(action, doc, user):
    apply_action_method = "/api/method/dataent.workflow.doctype.workflow_action.workflow_action.apply_action"

    params = {
        "doctype": doc.get('doctype'),
        "docname": doc.get('name'),
        "action": action,
        "current_state": get_doc_workflow_state(doc),
        "user": user,
        "last_modified": doc.get('modified')
    }

    return get_url(apply_action_method + "?" + get_signed_params(params))
예제 #12
0
	def execute_set_express_checkout(self, **kwargs):
		params, url = self.get_paypal_params_and_url()

		params.update({
			"METHOD": "SetExpressCheckout",
			"returnUrl": get_url("{0}.get_express_checkout_details".format(api_path)),
			"cancelUrl": get_url("/payment-cancel"),
			"PAYMENTREQUEST_0_PAYMENTACTION": "SALE",
			"PAYMENTREQUEST_0_AMT": kwargs['amount'],
			"PAYMENTREQUEST_0_CURRENCYCODE": kwargs['currency'].upper()
		})

		if kwargs.get('subscription_details'):
			self.configure_recurring_payments(params, kwargs)

		params = urlencode(params)
		response = make_post_request(url, data=params.encode("utf-8"))

		if response.get("ACK")[0] != "Success":
			dataent.throw(_("Looks like something is wrong with this site's Paypal configuration."))

		return response
예제 #13
0
def get_link_for_qrcode(user, totp_uri):
    '''Get link to temporary page showing QRCode.'''
    key = dataent.generate_hash(length=20)
    key_user = "******".format(key)
    key_uri = "{}_uri".format(key)
    lifespan = int(
        dataent.db.get_value('System Settings', 'System Settings',
                             'lifespan_qrcode_image'))
    if lifespan <= 0:
        lifespan = 240
    dataent.cache().set_value(key_uri, totp_uri, expires_in_sec=lifespan)
    dataent.cache().set_value(key_user, user, expires_in_sec=lifespan)
    return get_url('/qrcode?k={}'.format(key))
예제 #14
0
파일: queue.py 프로젝트: dataent/dataent
def get_unsubcribed_url(reference_doctype, reference_name, email, unsubscribe_method, unsubscribe_params):
	params = {"email": email.encode("utf-8"),
		"doctype": reference_doctype.encode("utf-8"),
		"name": reference_name.encode("utf-8")}
	if unsubscribe_params:
		params.update(unsubscribe_params)

	query_string = get_signed_params(params)

	# for test
	dataent.local.flags.signed_query_string = query_string

	return get_url(unsubscribe_method + "?" + get_signed_params(params))
예제 #15
0
def check_mandate(data, reference_doctype, reference_docname):
    data = json.loads(data)

    client = gocardless_initialization(reference_docname)

    payer = dataent.get_doc("Customer", data["payer_name"])

    if payer.customer_type == "Individual" and payer.customer_primary_contact is not None:
        primary_contact = dataent.get_doc("Contact",
                                          payer.customer_primary_contact)
        prefilled_customer = {
            "company_name": payer.name,
            "given_name": primary_contact.first_name,
        }
        if primary_contact.last_name is not None:
            prefilled_customer.update(
                {"family_name": primary_contact.last_name})

        if primary_contact.email_id is not None:
            prefilled_customer.update({"email": primary_contact.email_id})
        else:
            prefilled_customer.update({"email": dataent.session.user})

    else:
        prefilled_customer = {
            "company_name": payer.name,
            "email": dataent.session.user
        }

    success_url = get_url(
        "./integrations/gocardless_confirmation?reference_doctype=" +
        reference_doctype + "&reference_docname=" + reference_docname)

    try:
        redirect_flow = client.redirect_flows.create(
            params={
                "description":
                _("Pay {0} {1}".format(data['amount'], data['currency'])),
                "session_token":
                dataent.session.user,
                "success_redirect_url":
                success_url,
                "prefilled_customer":
                prefilled_customer
            })

        return {"redirect_to": redirect_flow.redirect_url}

    except Exception as e:
        dataent.log_error(e, "GoCardless Payment Error")
        return {"redirect_to": '/integrations/payment-failed'}
예제 #16
0
def get_attach_link(doc, print_format):
    """Returns public link for the attachment via `templates/emails/print_link.html`."""
    return dataent.get_template("templates/emails/print_link.html").render({
        "url":
        get_url(),
        "doctype":
        doc.reference_doctype,
        "name":
        doc.reference_name,
        "print_format":
        print_format,
        "key":
        get_parent_doc(doc).get_signature()
    })
예제 #17
0
def get_redirect_url():
	if not dataent.conf.dropbox_broker_site:
		dataent.conf.dropbox_broker_site = 'https://dropbox.epaas.xyz'
	url = "{0}/api/method/dropbox_epaas_broker.www.setup_dropbox.get_authotize_url".format(dataent.conf.dropbox_broker_site)

	try:
		response = make_post_request(url, data={"site": get_url()})
		if response.get("message"):
			return response["message"]

	except Exception:
		dataent.log_error()
		dataent.throw(
			_("Something went wrong while generating dropbox access token. Please check error log for more details.")
		)
예제 #18
0
def get_error_report(from_date=None, to_date=None, limit=10):
    from dataent.utils import get_url, now_datetime, add_days

    if not from_date:
        from_date = add_days(now_datetime().date(), -1)
    if not to_date:
        to_date = add_days(now_datetime().date(), -1)

    errors = get_errors(from_date, to_date, limit)

    if errors:
        return 1, """<h4>Error Logs (max {limit}):</h4>
			<p>URL: <a href="{url}" target="_blank">{url}</a></p><hr>{errors}""".format(
            limit=limit, url=get_url(), errors="<hr>".join(errors))
    else:
        return 0, "<p>No error logs</p>"
예제 #19
0
def setup_redirect(data, redirect_url, custom_redirect_to=None, redirect=True):
	redirect_to = data.get('redirect_to') or None
	redirect_message = data.get('redirect_message') or None

	if custom_redirect_to:
		redirect_to = custom_redirect_to

	if redirect_to:
		redirect_url += '&' + urlencode({'redirect_to': redirect_to})
	if redirect_message:
		redirect_url += '&' + urlencode({'redirect_message': redirect_message})

	# this is done so that functions called via hooks can update flags.redirect_to
	if redirect:
		dataent.local.response["type"] = "redirect"
		dataent.local.response["location"] = get_url(redirect_url)
예제 #20
0
def send_grant_review_emails(grant_application):
    grant = dataent.get_doc("Grant Application", grant_application)
    url = get_url('grant-application/{0}'.format(grant_application))
    dataent.sendmail(
        recipients=grant.assessment_manager,
        sender=dataent.session.user,
        subject='Grant Application for {0}'.format(grant.applicant_name),
        message='<p> Please Review this grant application</p><br>' + url,
        reference_doctype=grant.doctype,
        reference_name=grant.name)

    grant.status = 'In Progress'
    grant.email_notification_sent = 1
    grant.save()
    dataent.db.commit()

    dataent.msgprint(_("Review Invitation Sent"))
예제 #21
0
파일: project.py 프로젝트: dataent/epaas
    def send_welcome_email(self):
        url = get_url("/project/?name={0}".format(self.name))
        messages = (_(
            "You have been invited to collaborate on the project: {0}".format(
                self.name)), url, _("Join"))

        content = """
		<p>{0}.</p>
		<p><a href="{1}">{2}</a></p>
		"""

        for user in self.users:
            if user.welcome_email_sent == 0:
                dataent.sendmail(user.user,
                                 subject=_("Project Collaboration Invitation"),
                                 content=content.format(*messages))
                user.welcome_email_sent = 1
예제 #22
0
	def make(self):
		"""build into msg_root"""
		headers = {
			"Subject":        strip(self.subject),
			"From":           self.sender,
			"To":             ', '.join(self.recipients) if self.expose_recipients=="header" else "<!--recipient-->",
			"Date":           email.utils.formatdate(),
			"Reply-To":       self.reply_to if self.reply_to else None,
			"CC":             ', '.join(self.cc) if self.cc and self.expose_recipients=="header" else None,
			'X-Dataent-Site':  get_url(),
		}

		# reset headers as values may be changed.
		for key, val in iteritems(headers):
			self.set_header(key, val)

		# call hook to enable apps to modify msg_root before sending
		for hook in dataent.get_hooks("make_email_body_message"):
			dataent.get_attr(hook)(self)
예제 #23
0
	def test_site_expiry(self):
		user = dataent.get_doc('User', '*****@*****.**')
		user.enabled = 1
		user.new_password = '******'
		user.save()

		update_limits({'expiry': add_to_date(today(), days=-1), 'support_email': '*****@*****.**'})
		dataent.local.conf = _dict(dataent.get_site_config())

		dataent.db.commit()

		res = requests.post(get_url(), params={'cmd': 'login', 'usr':
			'******', 'pwd': 'Eastern_43A1W', 'device': 'desktop'})

		# While site is expired status code returned is 417 Failed Expectation
		self.assertEqual(res.status_code, 417)

		clear_limit("expiry")
		dataent.local.conf = _dict(dataent.get_site_config())
def set_redirect(razorpay_express_payment):
    """
		EPAAS related redirects.
		You need to set Razorpay Payment.flags.redirect_to on status change.
		Called via RazorpayPayment.on_update
	"""
    if "epaas" not in dataent.get_installed_apps():
        return

    if not razorpay_express_payment.flags.status_changed_to:
        return

    reference_doctype = razorpay_express_payment.reference_doctype
    reference_docname = razorpay_express_payment.reference_docname

    if not (reference_doctype and reference_docname):
        return

    reference_doc = dataent.get_doc(reference_doctype, reference_docname)
    shopping_cart_settings = dataent.get_doc("Shopping Cart Settings")

    if razorpay_express_payment.flags.status_changed_to == "Authorized":
        reference_doc.run_method("set_as_paid")

        # if shopping cart enabled and in session
        if (shopping_cart_settings.enabled
                and hasattr(dataent.local, "session")
                and dataent.local.session.user != "Guest"):

            success_url = shopping_cart_settings.payment_success_url
            if success_url:
                razorpay_express_payment.flags.redirect_to = ({
                    "Orders":
                    "orders",
                    "Invoices":
                    "invoices",
                    "My Account":
                    "me"
                }).get(success_url, "me")
            else:
                razorpay_express_payment.flags.redirect_to = get_url(
                    "/orders/{0}".format(reference_doc.reference_name))
예제 #25
0
    def send_welcome_mail_to_user(self):
        from dataent.utils import get_url
        link = self.reset_password()
        subject = None
        method = dataent.get_hooks("welcome_email")
        if method:
            subject = dataent.get_attr(method[-1])()
        if not subject:
            site_name = dataent.db.get_default(
                'site_name') or dataent.get_conf().get("site_name")
            if site_name:
                subject = _("Welcome to {0}".format(site_name))
            else:
                subject = _("Complete Registration")

        self.send_login_mail(subject, "new_user",
                             dict(
                                 link=link,
                                 site_url=get_url(),
                             ))
예제 #26
0
def qrcode_as_png(user, totp_uri):
    '''Save temporary Qrcode to server.'''
    from dataent.utils.file_manager import save_file
    folder = create_barcode_folder()
    png_file_name = '{}.png'.format(dataent.generate_hash(length=20))
    file_obj = save_file(png_file_name,
                         png_file_name,
                         'User',
                         user,
                         folder=folder)
    dataent.db.commit()
    file_url = get_url(file_obj.file_url)
    file_path = os.path.join(dataent.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
예제 #27
0
def get_feedback_request_url(reference_doctype,
                             reference_name,
                             recipients,
                             trigger="Manual"):
    """ prepare the feedback request url """
    is_manual = 1 if trigger == "Manual" else 0
    feedback_request = dataent.get_doc({
        "is_manual": is_manual,
        "feedback_trigger": trigger,
        "doctype": "Feedback Request",
        "reference_name": reference_name,
        "reference_doctype": reference_doctype,
    }).insert(ignore_permissions=True)

    feedback_url = "{base_url}/feedback?reference_doctype={doctype}&reference_name={docname}&email={email_id}&key={nonce}".format(
        base_url=get_url(),
        doctype=reference_doctype,
        docname=reference_name,
        email_id=recipients,
        nonce=feedback_request.key)

    return [feedback_request.name, feedback_url]
예제 #28
0
def _send_gstin_reminder(party_type,
                         party,
                         default_email_id=None,
                         sent_to=None):
    '''Send GST Reminder email'''
    email_id = dataent.db.get_value('Contact',
                                    get_default_contact(party_type, party),
                                    'email_id')
    if not email_id:
        # get email from address
        email_id = default_email_id

    if not email_id:
        dataent.throw(_('Email not found in default contact'),
                      exc=EmailMissing)

    if sent_to and email_id in sent_to:
        return

    dataent.sendmail(subject='Please update your GSTIN',
                     recipients=email_id,
                     message='''
		<p>Hello,</p>
		<p>Please help us send you GST Ready Invoices.</p>
		<p>
			<a href="{0}?party={1}">
			Click here to update your GSTIN Number in our system
			</a>
		</p>
		<p style="color: #aaa; font-size: 11px; margin-top: 30px;">
			Get your GST Ready ERP system at <a href="https://epaas.xyz">https://epaas.xyz</a>
			<br>
			EPAAS is a free and open source ERP system.
		</p>
		'''.format(os.path.join(get_url(), '/regional/india/update-gstin'), party))

    return email_id
예제 #29
0
 def get_payment_url(self, **kwargs):
     return get_url("./integrations/braintree_checkout?{0}".format(
         urlencode(kwargs)))
def get_checkout_url(**kwargs):
	missing_keys = set(expected_keys) - set(kwargs.keys())
	if missing_keys:
		dataent.throw(_('Missing keys to build checkout URL: {0}').format(", ".join(list(missing_keys))))

	return get_url('/razorpay_checkout?{0}'.format(urllib.urlencode(kwargs)))