Beispiel #1
0
def login_feed(login_manager):
	frappe.get_doc({
		"doctype": "Feed",
		"feed_type": "Login",
		"subject": _("{0} logged in").format(get_fullname(login_manager.user)),
		"full_name": get_fullname(login_manager.user)
	}).insert(ignore_permissions=True)
Beispiel #2
0
	def validate(self):
		if self.is_new():
			self.add_assign_comment(frappe._("Assigned to {0}: {1}").format(get_fullname(self.owner), self.description), "Assigned")
		else:
			cur_status = frappe.db.get_value("ToDo", self.name, "status")
			if cur_status != self.status:
				self.add_assign_comment(frappe._("Assignment closed by {0}".format(get_fullname(frappe.session.user))),
					"Assignment Completed")
Beispiel #3
0
	def validate(self):
		if self.is_new():
			self.add_assign_comment(frappe._("Assigned to {0}: {1}").format(get_fullname(self.owner), self.description), "Assigned")
		else:
			# NOTE the previous value is only available in validate method
			if self.get_db_value("status") != self.status:
				self.add_assign_comment(frappe._("Assignment closed by {0}".format(get_fullname(frappe.session.user))),
					"Assignment Completed")
Beispiel #4
0
	def after_insert(self):
		doc = self.get_doc()
		owner = get_fullname(self.owner)

		if self.everyone:
			doc.add_comment("Shared", _("{0} shared this document with everyone").format(owner))
		else:
			doc.add_comment("Shared", _("{0} shared this document with {1}").format(owner, get_fullname(self.user)))
Beispiel #5
0
	def on_update(self):
		from frappe.templates.website_group.post import clear_post_cache
		from frappe.website.doctype.website_group.website_group import clear_cache

		clear_cache(website_group=self.website_group)
		clear_post_cache(self.parent_post or self.name)

		if self.assigned_to and self.assigned_to != self.assigned_to \
			and frappe.session.user != self.assigned_to:

			# send assignment email
			sendmail(recipients=[self.assigned_to],
				subject="You have been assigned this Task by {}".format(get_fullname(self.modified_by)),
				msg=self.get_reply_email_message(self.name, get_fullname(self.owner)))
Beispiel #6
0
	def get_context(self, context):
		# this is for double precaution. usually it wont reach this code if not published
		if not cint(self.published):
			raise Exception, "This blog has not been published yet!"

		# temp fields
		context.full_name = get_fullname(self.owner)
		context.updated = global_date_format(self.published_on)

		if self.blogger:
			context.blogger_info = frappe.get_doc("Blogger", self.blogger).as_dict()

		context.description = self.blog_intro or self.content[:140]

		context.metatags = {
			"name": self.title,
			"description": context.description,
		}

		image = find_first_image(self.content)
		if image:
			context.metatags["image"] = image

		context.categories = frappe.db.sql_list("""select name from
			`tabBlog Category` order by name""")

		context.comment_list = get_comment_list(self.doctype, self.name)

		context.children = get_children()

		return context
Beispiel #7
0
	def make_new_lead_if_required(self):
		"""Set lead against new opportunity"""
		if not (self.lead or self.customer):
			lead_name = frappe.db.get_value("Lead", {"email_id": self.contact_email})
			if not lead_name:
				sender_name = get_fullname(self.contact_email)
				if sender_name == self.contact_email:
					sender_name = None

				account = _('Unknown')

				if self.contact_email.index('@'):
					email_name = self.contact_email[0:self.contact_email.index('@')]

					email_split = email_name.split('.')
					for s in email_split:
						account = account + s.capitalize() + ' '

				lead = frappe.get_doc({
					"doctype": "Lead",
					"email_id": self.contact_email,
					"lead_name": sender_name or account
				})
				lead.insert(ignore_permissions=True)
				lead_name = lead.name

			self.enquiry_from = "Lead"
			self.lead = lead_name
Beispiel #8
0
def get_context(context):
	blog_post = context.doc

	# this is for double precaution. usually it wont reach this code if not published
	if not cint(blog_post.published):
		raise Exception, "This blog has not been published yet!"

	# temp fields
	blog_post.full_name = get_fullname(blog_post.owner)
	blog_post.updated = global_date_format(blog_post.published_on)

	if blog_post.blogger:
		blog_post.blogger_info = frappe.get_doc("Blogger", blog_post.blogger).as_dict()

	blog_post.description = blog_post.blog_intro or blog_post.content[:140]

	blog_post.metatags = {
		"name": blog_post.title,
		"description": blog_post.description,
	}

	image = find_first_image(blog_post.content)
	if image:
		blog_post.metatags["image"] = image

	blog_post.categories = frappe.db.sql_list("select name from `tabBlog Category` order by name")

	blog_post.comment_list = frappe.db.sql("""\
		select comment, comment_by_fullname, creation
		from `tabComment` where comment_doctype="Blog Post"
		and comment_docname=%s order by creation""", (blog_post.name,), as_dict=1) or []

	return blog_post.__dict__
Beispiel #9
0
def notify(arg=None):
	from frappe.utils import cstr, get_fullname, get_url
	
	try:
		frappe.sendmail(\
			recipients=[frappe.db.get_value("User", arg["contact"], "email") or arg["contact"]],
			sender= frappe.db.get_value("User", frappe.session.user, "email"),
			subject="New Message from " + get_fullname(frappe.user.name),
			message=frappe.get_template("templates/emails/new_message.html").render({
				"from": get_fullname(frappe.user.name),
				"message": arg['txt'],
				"link": get_url()
			})
		)
	except frappe.OutgoingEmailError, e:
		pass
Beispiel #10
0
    def get_todo_list(self, user_id):
        todo_list = frappe.db.sql(
            """select *
			from `tabToDo` where (owner=%s or assigned_by=%s)
			order by field(priority, 'High', 'Medium', 'Low') asc, date asc""",
            (user_id, user_id),
            as_dict=True,
        )

        html = ""
        if todo_list:
            for i, todo in enumerate([todo for todo in todo_list if not todo.checked]):
                if i >= 10:
                    break
                if not todo.description and todo.reference_type:
                    todo.description = "%s: %s - %s %s" % (
                        todo.reference_type,
                        get_url_to_form(todo.reference_type, todo.reference_name),
                        _("assigned by"),
                        get_fullname(todo.assigned_by),
                    )

                html += "<li style='line-height: 200%%'>%s [%s]</li>" % (todo.description, todo.priority)

        if html:
            return 1, "<h4>To Do (max 10):</h4><ul>" + html + "</ul><hr>"
        else:
            return 0, "<p>To Do</p>"
Beispiel #11
0
def daily_notifications():
    """
        sent notifications to user if 
        1 : ticket is open for more than 24 hrs
        2 : ticket is assigned but not Closed in 24 hrs
    """
    tickets = frappe.db.get_all("Ticket Escalation History", filters=[["status", "!=", "Closed"], ["status", "!=", "Deleted"]], fields=["*"])
    for ticket in tickets:
        # ticket is raised but not yet assigned
        issue_doc = frappe.get_doc("Issue", ticket.ticket_id)
        args = {
            "user": get_fullname(issue_doc.raised_by) or "User",
            "email": issue_doc.raised_by,
            "action": "user_issue_notification",
            "issue": issue_doc
        }
        if ticket.raised_email_notification and not ticket.assigned_email_notification:
            raised_time = ticket.raised_email_notification_datetime
            if time_diff_in_hours(get_datetime().now(), raised_time) >= 24:
                # send user notification mail
                msg = "Your support ticket {ticket_id} is pending our representative will \
                check the issue as soon as possible".format(ticket_id=ticket.ticket_id)
                
                args.update({"msg":msg})
                send_mail(args, "[HelpDesk] Daily Notifications")
        elif ticket.assigned_email_notification and not ticket.status_closed_email_notification:
            assigned_time = ticket.assigned_email_notification_datetime
            if time_diff_in_hours(get_datetime().now(), assigned_time) >= 24:
                # send the user notification mail
                msg = "Your support ticket {ticket_id} is assigned to our support representative \
                and issue will be solved as soon as possble".format(ticket_id=ticket.ticket_id)
                
                args.update({"msg":msg})
                send_mail(args, "[HelpDesk] Daily Notifications")
Beispiel #12
0
	def make_new_lead_if_required(self):
		"""Set lead against new opportunity"""
		if not (self.lead or self.customer) and self.contact_email:
			lead_name = frappe.db.get_value("Lead", {"email_id": self.contact_email})
			if not lead_name:
				sender_name = get_fullname(self.contact_email)
				if sender_name == self.contact_email:
					sender_name = None

				if not sender_name and ('@' in self.contact_email):
					email_name = self.contact_email.split('@')[0]

					email_split = email_name.split('.')
					sender_name = ''
					for s in email_split:
						sender_name += s.capitalize() + ' '

				lead = frappe.get_doc({
					"doctype": "Lead",
					"email_id": self.contact_email,
					"lead_name": sender_name
				})

				lead.flags.ignore_email_validation = True
				lead.insert(ignore_permissions=True)
				lead_name = lead.name

			self.enquiry_from = "Lead"
			self.lead = lead_name
Beispiel #13
0
	def get_context(self, context):
		# this is for double precaution. usually it wont reach this code if not published
		if not cint(self.published):
			raise Exception, "This blog has not been published yet!"

		# temp fields
		context.full_name = get_fullname(self.owner)
		context.updated = global_date_format(self.published_on)

		if self.blogger:
			context.blogger_info = frappe.get_doc("Blogger", self.blogger).as_dict()

		context.description = self.blog_intro or self.content[:140]

		context.metatags = {
			"name": self.title,
			"description": context.description,
		}

		if "<!-- markdown -->" in context.content:
			context.content = markdown(context.content)

		image = find_first_image(self.content)
		if image:
			context.metatags["image"] = image

		context.comment_list = get_comment_list(self.doctype, self.name)

		context.children = get_children()

		category = frappe.db.get_value("Blog Category", context.doc.blog_category, ["title", "page_name"], as_dict=1)
		context.parents = [{"title": category.title, "name": "blog/{0}".format(category.page_name)}]
    def validate_leave_approver(self):
        employee = frappe.get_doc("Employee", self.employee)
        leave_approvers = [l.leave_approver for l in employee.get("leave_approvers")]

        if len(leave_approvers) and self.leave_approver not in leave_approvers:
            frappe.throw(
                _("Leave approver must be one of {0}").format(comma_or(leave_approvers)), InvalidLeaveApproverError
            )

        elif self.leave_approver and not frappe.db.sql(
            """select name from `tabUserRole`
			where parent=%s and role='Leave Approver'""",
            self.leave_approver,
        ):
            frappe.throw(
                _("{0} ({1}) must have role 'Leave Approver'").format(
                    get_fullname(self.leave_approver), self.leave_approver
                ),
                InvalidLeaveApproverError,
            )

        elif self.docstatus == 1 and len(leave_approvers) and self.leave_approver != frappe.session.user:
            frappe.throw(
                _("Only the selected Leave Approver can submit this Leave Application"), LeaveApproverIdentityError
            )
Beispiel #15
0
def update_feed(doc, method=None):
	"adds a new feed"
	if frappe.flags.in_patch or frappe.flags.in_install or frappe.flags.in_import:
		return

	if doc.doctype == "Feed":
		return

	if hasattr(doc, "get_feed"):
		feed = doc.get_feed()

		if feed:
			if isinstance(feed, basestring):
				feed = {"subject": feed}

			feed = frappe._dict(feed)
			doctype = feed.doctype or doc.doctype
			name = feed.name or doc.name

			# delete earlier feed
			frappe.db.sql("""delete from tabFeed
				where doc_type=%s and doc_name=%s
				and ifnull(feed_type,'')=''""", (doctype, name))

			frappe.get_doc({
				"doctype": "Feed",
				"feed_type": feed.feed_type or "",
				"doc_type": doctype,
				"doc_name": name,
				"subject": feed.subject,
				"full_name": get_fullname(doc.owner)
			}).insert(ignore_permissions=True)
Beispiel #16
0
def get_customer(user=None):
	if not user:
		user = frappe.session.user

	customer = frappe.db.get_value("Contact", {"email_id": user}, "customer")
	if customer:
		return frappe.get_doc("Customer", customer)

	else:
		customer = frappe.new_doc("Customer")
		fullname = get_fullname(user)
		customer.update({
			"customer_name": fullname,
			"customer_type": "Individual",
			"customer_group": get_shopping_cart_settings().default_customer_group,
			"territory": get_root_of("Territory")
		})
		customer.insert(ignore_permissions=True)

		contact = frappe.new_doc("Contact")
		contact.update({
			"customer": customer.name,
			"first_name": fullname,
			"email_id": user
		})
		contact.insert(ignore_permissions=True)

		return customer
Beispiel #17
0
def notify_mentions(doc):
	if doc.communication_type != "Comment":
		return

	if doc.reference_doctype and doc.reference_name and doc.content and doc.comment_type=="Comment":
		mentions = extract_mentions(doc.content)

		if not mentions:
			return

		sender_fullname = get_fullname(frappe.session.user)
		parent_doc_label = "{0} {1}".format(_(doc.reference_doctype), doc.reference_name)
		subject = _("{0} mentioned you in a comment in {1}").format(sender_fullname, parent_doc_label)
		message = frappe.get_template("templates/emails/mentioned_in_comment.html").render({
			"sender_fullname": sender_fullname,
			"comment": doc,
			"link": get_link_to_form(doc.reference_doctype, doc.reference_name, label=parent_doc_label)
		})

		recipients = [frappe.db.get_value("User", {"enabled": 1, "username": username, "user_type": "System User"})
			for username in mentions]

		frappe.sendmail(
			recipients=recipients,
			sender=frappe.session.user,
			subject=subject,
			message=message,
			bulk=True
		)
Beispiel #18
0
 def validate_expense_approver(self):
     if self.exp_approver and "Expense Approver" not in frappe.get_roles(self.exp_approver):
         frappe.throw(
             _("{0} ({1}) must have role 'Expense Approver'").format(
                 get_fullname(self.exp_approver), self.exp_approver
             ),
             InvalidExpenseApproverError,
         )
Beispiel #19
0
	def set_sender_full_name(self):
		if not self.sender_full_name and self.sender:
			if self.sender == "Administrator":
				self.sender_full_name = self.sender
				self.sender = frappe.db.get_value("User", "Administrator", "email")
			else:
				validate_email_add(self.sender, throw=True)
				self.sender_full_name = get_fullname(self.sender)
Beispiel #20
0
def _notify(contact, txt, subject=None):
	from frappe.utils import get_fullname, get_url

	try:
		if not isinstance(contact, list):
			contact = [frappe.db.get_value("User", contact, "email") or contact]
		frappe.sendmail(\
			recipients=contact,
			sender= frappe.db.get_value("User", frappe.session.user, "email"),
			subject=subject or "New Message from " + get_fullname(frappe.session.user),
			message=frappe.get_template("templates/emails/new_message.html").render({
				"from": get_fullname(frappe.session.user),
				"message": txt,
				"link": get_url()
			}))
	except frappe.OutgoingEmailError:
		pass
Beispiel #21
0
    def on_trash(self):
        if not self.flags.ignore_share_permission:
            self.check_share_permission()

        self.get_doc().add_comment(
            "Unshared",
            _("{0} un-shared this document with {1}").format(get_fullname(self.owner), get_fullname(self.user)),
        )
Beispiel #22
0
	def validate(self):
		"""Raise exception for more than 50 comments."""
		if frappe.db.sql("""select count(*) from tabComment where comment_doctype=%s
			and comment_docname=%s""", (self.doctype, self.name))[0][0] >= 50:
			frappe.throw(_("Cannot add more than 50 comments"))

		if not self.comment_by_fullname and self.comment_by:
			self.comment_by_fullname = get_fullname(self.comment_by)
Beispiel #23
0
	def _get_post_context():
		fullname = get_fullname(post.owner)
		return {
			"title": "{} by {}".format(post.title, fullname),
			"parent_post_html": get_parent_post_html(post, context),
			"post_list_html": get_child_posts_html(post, context),
			"parent_post": post.name
		}
Beispiel #24
0
def get_party(user=None):
	if not user:
		user = frappe.session.user

	contact_name = frappe.db.get_value("Contact", {"email_id": user})
	party = None

	if contact_name:
		contact = frappe.get_doc('Contact', contact_name)
		if contact.links:
			party_doctype = contact.links[0].link_doctype
			party = contact.links[0].link_name

	cart_settings = frappe.get_doc("Shopping Cart Settings")

	debtors_account = ''

	if cart_settings.enable_checkout:
		debtors_account = get_debtors_account(cart_settings)

	if party:
		return frappe.get_doc(party_doctype, party)

	else:
		if not cart_settings.enabled:
			frappe.local.flags.redirect_location = "/contact"
			raise frappe.Redirect
		customer = frappe.new_doc("Customer")
		fullname = get_fullname(user)
		customer.update({
			"customer_name": fullname,
			"customer_type": "Individual",
			"customer_group": get_shopping_cart_settings().default_customer_group,
			"territory": get_root_of("Territory")
		})

		if debtors_account:
			customer.update({
				"accounts": [{
					"company": cart_settings.company,
					"account": debtors_account
				}]
			})

		customer.flags.ignore_mandatory = True
		customer.insert(ignore_permissions=True)

		contact = frappe.new_doc("Contact")
		contact.update({
			"first_name": fullname,
			"email_id": user
		})
		contact.append('links', dict(link_doctype='Customer', link_name=customer.name))
		contact.flags.ignore_mandatory = True
		contact.insert(ignore_permissions=True)

		return customer
def execute():
	for user_id in frappe.db.sql_list("""select distinct user_id from `tabEmployee`
		where ifnull(user_id, '')!=''
		group by user_id having count(name) > 1"""):
		
		fullname = get_fullname(user_id)
		employee = frappe.db.get_value("Employee", {"employee_name": fullname, "user_id": user_id})
		if employee:
			frappe.db.sql("""update `tabEmployee` set user_id=null
				where user_id=%s and name!=%s""", (user_id, employee))
Beispiel #26
0
def get_user_details(user):
	from frappe.utils import get_fullname

	# fields = ["city", "building", "area", "facility", "description"]
	details = frappe.db.get_value("User", user, as_dict=True)
	if details:
		details.update({"user_fullname":get_fullname(user) or ""})
		return details
	else:
		return {}
Beispiel #27
0
def get_user_details(user):
	from frappe.utils import get_fullname

	fields = ["floor", "extension_number", "wing", "cabin_or_workstation_number", "department"]
	details = frappe.db.get_value("User", user, fields, as_dict=True)
	if details:
		details.update({"user_fullname":get_fullname(user) or ""})
		return details
	else:
		return {}
Beispiel #28
0
def _notify(contact, txt, subject=None):
	from frappe.utils import get_fullname, get_url

	try:
		if not isinstance(contact, list):
			contact = [frappe.db.get_value("User", contact, "email") or contact]
		frappe.sendmail(\
			recipients=contact,
			sender= frappe.db.get_value("User", frappe.session.user, "email"),
			subject=subject or _("New Message from {0}").format(get_fullname(frappe.session.user)),
			template="new_message",
			args={
				"from": get_fullname(frappe.session.user),
				"message": txt,
				"link": get_url()
			},
			header=[_('New Message'), 'orange'])
	except frappe.OutgoingEmailError:
		pass
Beispiel #29
0
def get_context(context):
	data = frappe.db.sql("""select count(*) as translated, modified_by
		from `tabTranslated Message`
		where modified_by != "Administrator"
		group by modified_by order by translated desc limit 20""", as_dict=1)

	for d in data:
		d.fullname = get_fullname(d.modified_by)

	context.users = data
	def set_sender_full_name(self):
		if not self.sender_full_name and self.sender:
			if self.sender == "Administrator":
				self.sender_full_name = self.sender
				self.sender = frappe.db.get_value("User", "Administrator", "email")
			elif self.sender == "Guest":
				self.sender_full_name = self.sender
				self.sender = None
			else:
				validate_email_add(self.sender, throw=True)

				sender_name, sender_email = parseaddr(self.sender)

				if not sender_name:
					sender_name = get_fullname(sender_email)
					if sender_name == sender_email:
						sender_name = None

				self.sender = sender_email
				self.sender_full_name = sender_name or get_fullname(frappe.session.user)
Beispiel #31
0
def _notify(args):
	from frappe.utils import get_fullname, get_url

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

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

		frappe.sendmail(\
			recipients=contact,
			sender= frappe.db.get_value("User", frappe.session.user, "email"),
			subject=_("New message from {0}").format(get_fullname(frappe.session.user)),
			template="new_message",
			args={
				"from": get_fullname(frappe.session.user),
				"message": txt,
				"link": get_url()
			},
			header=[_('New Message'), 'orange'])
	except frappe.OutgoingEmailError:
		pass
Beispiel #32
0
    def set_title(self):
        """Set default title for the Time Log"""
        if self.title:
            return

        from frappe.utils import get_fullname
        if self.production_order:
            self.title = _("{0} for {1}").format(self.operation,
                                                 self.production_order)
        elif self.activity_type and (self.task or self.project):
            self.title = _("{0} for {1}").format(self.activity_type, self.task
                                                 or self.project)
        else:
            self.title = self.task or self.project or get_fullname(
                frappe.session.user)
Beispiel #33
0
	def send_email_on_reply(self):
		owner_fullname = get_fullname(self.owner)

		parent_post = frappe.get_doc("Post", self.parent_post)

		message = self.get_reply_email_message(self.name, owner_fullname)

		# send email to the owner of the post, if he/she is different
		if parent_post.owner != self.owner:
			send(recipients=[parent_post.owner],
				subject="{someone} replied to your post".format(someone=owner_fullname),
				message=message,

				# to allow unsubscribe
				doctype='Post',
				email_field='owner',

				# for tracking sent status
				ref_doctype=self.doctype, ref_docname=self.name)

		# send email to members who part of the conversation
		participants = frappe.db.sql("""select owner, name from `tabPost`
			where parent_post=%s and owner not in (%s, %s) order by creation asc""",
			(self.parent_post, parent_post.owner, self.owner), as_dict=True)

		send(recipients=[p.owner for p in participants],
			subject="{someone} replied to a post by {other}".format(someone=owner_fullname,
				other=get_fullname(parent_post.owner)),
			message=message,

			# to allow unsubscribe
			doctype='Post',
			email_field='owner',

			# for tracking sent status
			ref_doctype=self.doctype, ref_docname=self.name)
Beispiel #34
0
def execute():
	for user_id in frappe.db.sql_list("""select distinct user_id from `tabEmployee`
		where ifnull(user_id, '')!=''
		group by user_id having count(name) > 1"""):

		fullname = get_fullname(user_id)
		employee = frappe.db.get_value("Employee", {"employee_name": fullname, "user_id": user_id})

		if employee:
			frappe.db.sql("""update `tabEmployee` set user_id=null
				where user_id=%s and name!=%s""", (user_id, employee))
		else:
			count = frappe.db.sql("""select count(*) from `tabEmployee` where user_id=%s""", user_id)[0][0]
			frappe.db.sql("""update `tabEmployee` set user_id=null
				where user_id=%s limit %s""", (user_id, count - 1))
Beispiel #35
0
def get_context(context):
    context.no_cache = True
    data = frappe.db.sql("""SELECT count(*) AS contribution_count, modified_by
		FROM `tabTranslated Message`
		WHERE modified_by != "Administrator"
		GROUP BY modified_by
		ORDER BY contribution_count
		DESC LIMIT 50
	""",
                         as_dict=1)

    for d in data:
        d.fullname = get_fullname(d.modified_by)

    context.users = data
Beispiel #36
0
def insert_feed(doc):
    from frappe.utils import get_fullname

    if frappe.flags.in_install or frappe.flags.in_import or getattr(
            doc, "no_feed_on_delete", False):
        return

    frappe.get_doc({
        "doctype": "Feed",
        "feed_type": "Label",
        "doc_type": doc.doctype,
        "doc_name": doc.name,
        "subject": _("Deleted"),
        "full_name": get_fullname(doc.owner)
    }).insert(ignore_permissions=True)
	def validate_leave_approver(self):
		employee = frappe.get_doc("Employee", self.employee)
		leave_approvers = [l.leave_approver for l in employee.get("employee_leave_approvers")]

		if len(leave_approvers) and self.leave_approver not in leave_approvers:
			frappe.throw(_("Leave approver must be one of {0}").format(comma_or(leave_approvers)), InvalidLeaveApproverError)

		elif self.leave_approver and not frappe.db.sql("""select name from `tabUserRole`
			where parent=%s and role='Leave Approver'""", self.leave_approver):
			frappe.throw(_("{0} ({1}) must have role 'Leave Approver'")\
				.format(get_fullname(self.leave_approver), self.leave_approver), InvalidLeaveApproverError)

		elif self.docstatus==1 and len(leave_approvers) and self.leave_approver != frappe.session.user:
			msgprint(_("Only the selected Leave Approver can submit this Leave Application"),
				raise_exception=LeaveApproverIdentityError)
Beispiel #38
0
def insert_feed(doc):
    from frappe.utils import get_fullname

    if frappe.flags.in_install or frappe.flags.in_import or getattr(
            doc, "no_feed_on_delete", False):
        return

    frappe.get_doc({
        "doctype": "Communication",
        "communication_type": "Comment",
        "comment_type": "Deleted",
        "reference_doctype": doc.doctype,
        "subject": "{0} {1}".format(_(doc.doctype), doc.name),
        "full_name": get_fullname(doc.owner)
    }).insert(ignore_permissions=True)
	def make_new_lead_if_required(self):
		"""Set lead against new opportunity"""
		if not (self.lead or self.customer) and self.contact_email:
			# check if customer is already created agains the self.contact_email
			customer = frappe.db.sql("""select
				distinct `tabDynamic Link`.link_name as customer
				from
					`tabContact`,
					`tabDynamic Link`
				where `tabContact`.email_id='{0}'
				and
					`tabContact`.name=`tabDynamic Link`.parent
				and
					ifnull(`tabDynamic Link`.link_name, '')<>''
				and
					`tabDynamic Link`.link_doctype='Customer'
			""".format(self.contact_email), as_dict=True)
			if customer and customer[0].customer:
				self.customer = customer[0].customer
				self.enquiry_from = "Customer"
				return

			lead_name = frappe.db.get_value("Lead", {"email_id": self.contact_email})
			if not lead_name:
				sender_name = get_fullname(self.contact_email)
				if sender_name == self.contact_email:
					sender_name = None

				if not sender_name and ('@' in self.contact_email):
					email_name = self.contact_email.split('@')[0]

					email_split = email_name.split('.')
					sender_name = ''
					for s in email_split:
						sender_name += s.capitalize() + ' '

				lead = frappe.get_doc({
					"doctype": "Lead",
					"email_id": self.contact_email,
					"lead_name": sender_name or 'Unknown'
				})

				lead.flags.ignore_email_validation = True
				lead.insert(ignore_permissions=True)
				lead_name = lead.name

			self.enquiry_from = "Lead"
			self.lead = lead_name
Beispiel #40
0
def info(_w_appid, _w_access_key, _w_conf_name, _w_conf_version,
         _w_conf_version_new, _w_signature):
    valid_auth_code(_w_access_key)
    _w_conf_name = _w_conf_name or frappe.get_request_header(
        "x-weboffice-file-id")

    conf_doc = frappe.get_doc("IOT Application Conf", _w_conf_name)
    if conf_doc.public == 0 and conf_doc.developer != frappe.session.user:
        throw("has_no_permission")

    data = app_conf_data(conf_doc.name, _w_conf_version)
    creation = get_datetime(conf_doc.creation)
    modified = get_datetime((conf_doc.modified))


    params = "_w_appid=" + _w_appid + "&_w_conf_name=" + _w_conf_name + "&_w_conf_version=" + _w_conf_version + \
             "&_w_conf_version_new=" + _w_conf_version_new + "&_w_access_key=" + _w_access_key

    file_info = {
        "id":
        _w_conf_name,
        "name":
        conf_doc.app + "-" + conf_doc.name + ".csv",
        "version":
        int(_w_conf_version_new),
        "size":
        len(data.get('data') or ''),
        "creator":
        conf_doc.owner,
        "create_time":
        int(creation.timestamp()),
        "modifier":
        conf_doc.developer,
        "modify_time":
        int(modified.timestamp()),
        "download_url":
        "https://cloud.thingsroot.com/v1/3rd/file/content?" + params
    }
    user_info = {
        "id":
        frappe.session.user,
        "name":
        get_fullname(frappe.session.user),
        "permission":
        "write" if conf_doc.developer == frappe.session.user else "read"
    }

    frappe.response.update({"file": file_info, "user": user_info})
Beispiel #41
0
	def get_context(self, context):
		# this is for double precaution. usually it wont reach this code if not published
		if not cint(self.published):
			raise Exception("This blog has not been published yet!")

		context.no_breadcrumbs = True

		# temp fields
		context.full_name = get_fullname(self.owner)
		context.updated = global_date_format(self.published_on)
		context.social_links = self.fetch_social_links_info()
		context.cta = self.fetch_cta()
		context.enable_cta = not self.hide_cta and frappe.db.get_single_value(
			"Blog Settings", "show_cta_in_blog", cache=True
		)

		if self.blogger:
			context.blogger_info = frappe.get_doc("Blogger", self.blogger).as_dict()
			context.author = self.blogger

		context.content = get_html_content_based_on_type(self, "content", self.content_type)

		# if meta description is not present, then blog intro or first 140 characters of the blog will be set as description
		context.description = (
			self.meta_description or self.blog_intro or strip_html_tags(context.content[:140])
		)

		context.metatags = {
			"name": self.meta_title,
			"description": context.description,
		}

		# if meta image is not present, then first image inside the blog will be set as the meta image
		image = find_first_image(context.content)
		context.metatags["image"] = self.meta_image or image or None

		self.load_comments(context)
		self.load_feedback(context)

		context.category = frappe.db.get_value(
			"Blog Category", context.doc.blog_category, ["title", "route"], as_dict=1
		)
		context.parents = [
			{"name": _("Home"), "route": "/"},
			{"name": "Blog", "route": "/blog"},
			{"label": context.category.title, "route": context.category.route},
		]
		context.guest_allowed = True
Beispiel #42
0
	def set_sender_full_name(self):
		if not self.sender_full_name and self.sender:
			if self.sender == "Administrator":
				self.sender_full_name = frappe.db.get_value("User", "Administrator", "full_name")
				self.sender = frappe.db.get_value("User", "Administrator", "email")
			elif self.sender == "Guest":
				self.sender_full_name = self.sender
				self.sender = None
			else:
				if self.sent_or_received=='Sent':
					validate_email_add(self.sender, throw=True)
				sender_name, sender_email = parse_addr(self.sender)
				if sender_name == sender_email:
					sender_name = None
				self.sender = sender_email
				self.sender_full_name = sender_name or get_fullname(frappe.session.user) if frappe.session.user!='Administrator' else None
Beispiel #43
0
    def get_context(self, context):
        # this is for double precaution. usually it wont reach this code if not published
        if not cint(self.published):
            raise Exception, "This blog has not been published yet!"

        # temp fields
        context.full_name = get_fullname(self.owner)
        context.updated = global_date_format(self.published_on)

        if self.blogger:
            context.blogger_info = frappe.get_doc("Blogger",
                                                  self.blogger).as_dict()

        context.description = self.blog_intro or self.content[:140]

        context.metatags = {
            "name": self.title,
            "description": context.description,
        }

        if "<!-- markdown -->" in context.content:
            context.content = markdown(context.content)

        image = find_first_image(self.content)
        if image:
            context.metatags["image"] = image

        context.comment_list = get_comment_list(self.doctype, self.name)
        if not context.comment_list:
            context.comment_text = _('No comments yet')
        else:
            if (len(context.comment_list)) == 1:
                context.comment_text = _('1 comment')
            else:
                context.comment_text = _('{0} comments').format(
                    len(context.comment_list))

        context.children = get_children()

        category = frappe.db.get_value("Blog Category",
                                       context.doc.blog_category,
                                       ["title", "page_name"],
                                       as_dict=1)
        context.parents = [{
            "title": category.title,
            "name": "blog/{0}".format(category.page_name)
        }]
Beispiel #44
0
def get_customer(user=None):
    if not user:
        user = frappe.session.user

    customer = frappe.db.get_value("Contact", {"email_id": user}, "customer")
    cart_settings = frappe.get_doc("Shopping Cart Settings")

    debtors_account = ''

    if cart_settings.enable_checkout:
        debtors_account = get_debtors_account(cart_settings)

    if customer:
        return frappe.get_doc("Customer", customer)

    else:
        customer = frappe.new_doc("Customer")
        fullname = get_fullname(user)
        customer.update({
            "customer_name": fullname,
            "customer_type": "Individual",
            "customer_group":
            get_shopping_cart_settings().default_customer_group,
            "territory": get_root_of("Territory")
        })

        if debtors_account:
            customer.update({
                "accounts": [{
                    "company": cart_settings.company,
                    "account": debtors_account
                }]
            })

        customer.flags.ignore_mandatory = True
        customer.insert(ignore_permissions=True)

        contact = frappe.new_doc("Contact")
        contact.update({
            "customer": customer.name,
            "first_name": fullname,
            "email_id": user
        })
        contact.flags.ignore_mandatory = True
        contact.insert(ignore_permissions=True)

        return customer
Beispiel #45
0
def randomly_assign(docs):
    from frappe.desk.form.assign_to import add

    # USAGE
    #
    # args = {
    #     "assign_to": ,
    #     "doctype": ,
    #     "name": ,
    #     "description":
    # }

    if isinstance(docs, basestring):
        import json
        docs = json.loads(docs)

    from frappe import get_all, bold, _

    collector_users = [d.user for d in \
     get_all("Case Record Settings User",
      fields=["user"])]

    import random

    random.shuffle(collector_users)

    length = len(collector_users)

    idx = 0

    from frappe.utils import cint, get_fullname

    for doctype, name in docs:
        random.shuffle(collector_users)

        collector_user = collector_users[cint((idx + length)**length % length)]

        add({
            "assign_to": collector_user,
            "doctype": doctype,
            "name": name,
            "description": _("Randomly assigned by {}" \
          .format(bold(get_fullname())))
        })

        idx += 1
Beispiel #46
0
def update_feed(doc, method=None):
    if frappe.flags.in_patch or frappe.flags.in_install or frappe.flags.in_import:
        return

    if doc._action != "save" or doc.flags.ignore_feed:
        return

    if doc.doctype == "Activity Log" or doc.meta.issingle:
        return

    if hasattr(doc, "get_feed"):
        feed = doc.get_feed()

        if feed:
            if isinstance(feed, string_types):
                feed = {"subject": feed}

            feed = frappe._dict(feed)
            doctype = feed.doctype or doc.doctype
            name = feed.name or doc.name

            # delete earlier feed
            frappe.db.sql(
                """delete from `tabActivity Log`
				where
					reference_doctype=%s and reference_name=%s
					and link_doctype=%s""", (doctype, name, feed.link_doctype))
            frappe.get_doc({
                "doctype":
                "Activity Log",
                "reference_doctype":
                doctype,
                "reference_name":
                name,
                "subject":
                feed.subject,
                "full_name":
                get_fullname(doc.owner),
                "reference_owner":
                frappe.db.get_value(doctype, name, "owner"),
                "link_doctype":
                feed.link_doctype,
                "link_name":
                feed.link_name
            }).insert(ignore_permissions=True)
Beispiel #47
0
def update_feed(doc, method=None):
    "adds a new feed"
    if frappe.flags.in_patch or frappe.flags.in_install or frappe.flags.in_import:
        return

    if doc.doctype == "Feed" or doc.meta.issingle:
        return

    if hasattr(doc, "get_feed"):
        feed = doc.get_feed()

        if feed:
            if isinstance(feed, basestring):
                feed = {"subject": feed}

            feed = frappe._dict(feed)
            doctype = feed.doctype or doc.doctype
            name = feed.name or doc.name

            # delete earlier feed
            frappe.db.sql(
                """delete from tabFeed
				where doc_type=%s and doc_name=%s
				and ifnull(feed_type,'')=''""", (doctype, name))

            frappe.get_doc({
                "doctype":
                "Feed",
                "feed_type":
                feed.feed_type or "",
                "doc_type":
                doctype,
                "doc_name":
                name,
                "subject":
                feed.subject,
                "full_name":
                get_fullname(doc.owner),
                "doc_owner":
                frappe.db.get_value(doctype, name, "owner"),
                "reference_doctype":
                feed.reference_doctype,
                "reference_name":
                feed.reference_name
            }).insert(ignore_permissions=True)
Beispiel #48
0
def get_upgrade_url(upgrade_url):
    parts = urlparse.urlsplit(upgrade_url)
    params = dict(urlparse.parse_qsl(parts.query))
    params.update({
        'site':
        frappe.local.site,
        'email':
        frappe.session.user,
        'full_name':
        get_fullname(),
        'country':
        frappe.db.get_value("System Settings", "System Settings", 'country')
    })

    query = urllib.urlencode(params, doseq=True)
    url = urlparse.urlunsplit(
        (parts.scheme, parts.netloc, parts.path, query, parts.fragment))
    return url
Beispiel #49
0
def validate_leave_approver(employee, leave_approver, docstatus):
    e = frappe.get_doc("Employee", employee)
    leave_approvers = [l.leave_approver for l in e.get("leave_approvers")]

    if len(leave_approvers) and leave_approver not in leave_approvers:
        return "Leave approver must be one of {0}".format(
            comma_or(leave_approvers))

    elif leave_approver and not frappe.db.sql(
            """select name from `tabHas Role`
		where parent=%s and role='Leave Approver'""", leave_approver):
        return "{0} ({1}) must have role 'Leave Approver'".format(
            get_fullname(leave_approver), leave_approver)

    elif docstatus == 1 and len(
            leave_approvers) and leave_approver != frappe.session.user:
        return "Only the selected Leave Approver can submit this Leave Application"
    return ""
Beispiel #50
0
def append_task_report(taskname, template_name, state=None, doc=None):
    doc = doc or frappe.get_doc("Task", taskname)
    project = doc.get("project")
    task = doc.get("name")
    user_allocated = frappe.get_value("ToDo", {
        "reference_type": "Task",
        "reference_name": doc.get("name")
    }, "owner") or doc.get("owner")
    implementer = get_fullname(user_allocated)
    starts = doc.get("exp_start_date") or "unspecified"
    ends = doc.get("exp_end_date") or "unspecified"

    completed = [
        x.get("task") for x in doc.get("depends_on")
        if x.get("status") == "Completed"
    ]
    all_tasks = [x.get("task") for x in doc.get("depends_on")]
    #frappe.throw(str(len(completed)))
    #frappe.throw(str(len(all_tasks)))
    percent = len(completed) or 0.0 * 100 / len(all_tasks) or 0.0

    period = f"{starts} to {ends}"
    percent_progress = int(doc.get("progress"))
    progress = f"{percent_progress} %"
    priority = doc.get("priority")
    status = doc.get("status")

    activities = "<p>--</p>"
    if doc.get("depends_on"):
        activities = "<table style='width:100%;border:1px;padding: 0;margin: 0;border-collapse: collapse;border-spacing:0;'><tr><td>ID</td><td>Subject</td><td>Status</td><td>Remarks</td></tr>"
        for d in doc.get("depends_on"):
            t_name = d.get("task")
            subj = d.get("subject")
            stat = d.get("status") or ""
            remarks = d.get("remarks") or "-"
            activities += f"<tr><td>{t_name}</td><td>{subj}</td><td>{stat}</td><td><b>Remarks:</b> {remarks}</td></tr>"
        activities += "</table>"

    template = frappe.get_doc("Document Template", template_name)
    text = template.get("part_a")
    text2 = eval(f"f'{text}'")
    if (state):
        doc.set("description", text2)
    return text2
Beispiel #51
0
    def get_context(self, context):
        # this is for double precaution. usually it wont reach this code if not published
        if not cint(self.published):
            raise Exception("This blog has not been published yet!")

        # temp fields
        context.full_name = get_fullname(self.owner)
        context.updated = global_date_format(self.published_on)

        if self.blogger:
            context.blogger_info = frappe.get_doc("Blogger",
                                                  self.blogger).as_dict()
            context.author = self.blogger

        context.content = get_html_content_based_on_type(
            self, 'content', self.content_type)
        context.description = self.blog_intro or strip_html_tags(
            context.content[:140])

        context.metatags = {
            "name": self.title,
            "description": context.description,
        }

        image = find_first_image(context.content)
        if image:
            context.metatags["image"] = image

        self.load_comments(context)

        context.category = frappe.db.get_value("Blog Category",
                                               context.doc.blog_category,
                                               ["title", "route"],
                                               as_dict=1)
        context.parents = [{
            "name": _("Home"),
            "route": "/"
        }, {
            "name": "Blog",
            "route": "/blog"
        }, {
            "label": context.category.title,
            "route": context.category.route
        }]
Beispiel #52
0
def post(txt, contact, parenttype=None, notify=False, subject=None):
	import frappe
	"""post message"""

	d = frappe.new_doc('Comment')
	d.parenttype = parenttype
	d.comment = txt
	d.comment_docname = contact
	d.comment_doctype = 'Message'
	d.comment_by_fullname = get_fullname(frappe.session.user)
	d.insert(ignore_permissions=True)

	delete_notification_count_for("Messages")

	if notify and cint(notify):
		if contact==frappe.session.user:
			_notify([user.name for user in get_enabled_system_users()], txt)
		else:
			_notify(contact, txt, subject)
Beispiel #53
0
    def make_new_lead_if_required(self):
        """Set lead against new opportunity"""
        if (not self.get("party_name")) and self.contact_email:
            # check if customer is already created agains the self.contact_email
            dynamic_link, contact = DocType("Dynamic Link"), DocType("Contact")
            customer = (frappe.qb.from_(dynamic_link).join(contact).on(
                (contact.name == dynamic_link.parent)
                & (dynamic_link.link_doctype == "Customer")
                & (contact.email_id == self.contact_email)).select(
                    dynamic_link.link_name).distinct().run(as_dict=True))

            if customer and customer[0].link_name:
                self.party_name = customer[0].link_name
                self.opportunity_from = "Customer"
                return

            lead_name = frappe.db.get_value("Lead",
                                            {"email_id": self.contact_email})
            if not lead_name:
                sender_name = get_fullname(self.contact_email)
                if sender_name == self.contact_email:
                    sender_name = None

                if not sender_name and ("@" in self.contact_email):
                    email_name = self.contact_email.split("@")[0]

                    email_split = email_name.split(".")
                    sender_name = ""
                    for s in email_split:
                        sender_name += s.capitalize() + " "

                lead = frappe.get_doc({
                    "doctype": "Lead",
                    "email_id": self.contact_email,
                    "lead_name": sender_name or "Unknown"
                })

                lead.flags.ignore_email_validation = True
                lead.insert(ignore_permissions=True)
                lead_name = lead.name

            self.opportunity_from = "Lead"
            self.party_name = lead_name
	def _get_party(user):
		customer = frappe.db.get_value("Contact", {"email_id": user}, "customer")
		if customer:
			return frappe.get_doc("Customer", customer)

		lead = frappe.db.get_value("Lead", {"email_id": user})
		if lead:
			return frappe.get_doc("Lead", lead)

		# create a lead
		lead = frappe.new_doc("Lead")
		lead.update({
			"email_id": user,
			"lead_name": get_fullname(user),
			"territory": guess_territory()
		})
		lead.insert(ignore_permissions=True)

		return lead
Beispiel #55
0
def log_invalid_item(item):
    frappe.db.sql(
        """delete from `tabCommunication`
					where
						reference_doctype=%s and reference_name=%s
						and communication_type='Comment'
						and comment_type='Cancelled'""", ("Item", item.name))

    frappe.get_doc({
        "doctype": "Communication",
        "communication_type": "Comment",
        "comment_type": "Cancelled",
        "reference_doctype": "Item",
        "reference_name": item.name,
        "subject": item.item_name,
        "full_name": get_fullname(item.owner),
        "reference_owner": item.owner,
        # "link_doctype": "Item",
        # "link_name": item.name
    }).insert(ignore_permissions=True)
Beispiel #56
0
def get_alert_dict(doc):
    alert_dict = frappe._dict()
    owner_name = get_fullname(doc.owner)
    if doc.reference_doctype:
        doc_link = get_link_to_form(doc.reference_doctype, doc.reference_name)
    points = doc.points
    bold_points = frappe.bold(doc.points)
    if doc.type == "Auto":
        if points == 1:
            message = _("You gained {0} point")
        else:
            message = _("You gained {0} points")
        alert_dict.message = message.format(bold_points)
        alert_dict.indicator = "green"
    elif doc.type == "Appreciation":
        if points == 1:
            message = _("{0} appreciated your work on {1} with {2} point")
        else:
            message = _("{0} appreciated your work on {1} with {2} points")
        alert_dict.message = message.format(owner_name, doc_link, bold_points)
        alert_dict.indicator = "green"
    elif doc.type == "Criticism":
        if points == 1:
            message = _("{0} criticized your work on {1} with {2} point")
        else:
            message = _("{0} criticized your work on {1} with {2} points")

        alert_dict.message = message.format(owner_name, doc_link, bold_points)
        alert_dict.indicator = "red"
    elif doc.type == "Revert":
        if points == 1:
            message = _("{0} reverted your point on {1}")
        else:
            message = _("{0} reverted your points on {1}")
        alert_dict.message = message.format(
            owner_name,
            doc_link,
        )
        alert_dict.indicator = "red"

    return alert_dict
Beispiel #57
0
def get_alert_dict(doc):
    alert_dict = frappe._dict()
    owner_name = get_fullname(doc.owner)
    if doc.reference_doctype:
        doc_link = get_link_to_form(doc.reference_doctype, doc.reference_name)
    points = doc.points
    bold_points = frappe.bold(doc.points)
    if doc.type == 'Auto':
        if points == 1:
            message = _('You gained {0} point')
        else:
            message = _('You gained {0} points')
        alert_dict.message = message.format(bold_points)
        alert_dict.indicator = 'green'
    elif doc.type == 'Appreciation':
        if points == 1:
            message = _('{0} appreciated your work on {1} with {2} point')
        else:
            message = _('{0} appreciated your work on {1} with {2} points')
        alert_dict.message = message.format(owner_name, doc_link, bold_points)
        alert_dict.indicator = 'green'
    elif doc.type == 'Criticism':
        if points == 1:
            message = _('{0} criticized your work on {1} with {2} point')
        else:
            message = _('{0} criticized your work on {1} with {2} points')

        alert_dict.message = message.format(owner_name, doc_link, bold_points)
        alert_dict.indicator = 'red'
    elif doc.type == 'Revert':
        if points == 1:
            message = _('{0} reverted your point on {1}')
        else:
            message = _('{0} reverted your points on {1}')
        alert_dict.message = message.format(
            owner_name,
            doc_link,
        )
        alert_dict.indicator = 'red'

    return alert_dict
Beispiel #58
0
def info(_w_appid, _w_conf_name, _w_access_key, _w_signature):
	valid_auth_code(_w_access_key)
	_w_conf_name = _w_conf_name or frappe.get_request_header("x-weboffice-file-id")

	data = get_post_json_data()

	ids = data.get('ids')
	if ids:
		users = []
		for id in ids:
			users.append({
				"id": id,
				"name":  get_fullname(id),
				"avatar_url": "http://cloud.thingsroot.com/user?id=" + id
			})

		frappe.response.update({
			"users": users
		})
	else:
		throw("missing_ids")
Beispiel #59
0
	def validate(self):
		if not self.parent_post and not self.title:
			frappe.throw(_("Title is required"))

		self.assigned_to = frappe.db.get_value(self.doctype, self.name, "assigned_to")
		if self.is_task:
			if not self.status:
				self.status = "Open"
			if self.assigned_to:
				if not self.assigned_to_fullname:
					self.assigned_to_fullname = get_fullname(self.assigned_to)
			else:
				self.assigned_to_fullname = None
		else:
			self.assigned_to = self.assigned_to_fullname = self.status = None

		if self.is_event:
			if not self.event_datetime:
				frappe.throw(_("Please specify Event date and time"))
		else:
			self.event_datetime = None
Beispiel #60
0
def notify_assignment(shared_by, doctype, doc_name, everyone):

	if not (shared_by and doctype and doc_name) or everyone: return

	from frappe.utils import get_fullname

	title = get_title(doctype, doc_name)

	reference_user = get_fullname(frappe.session.user)
	notification_message = _('{0} shared a document {1} {2} with you').format(
		frappe.bold(reference_user), frappe.bold(doctype), get_title_html(title))

	notification_doc = {
		'type': 'Share',
		'document_type': doctype,
		'subject': notification_message,
		'document_name': doc_name,
		'from_user': frappe.session.user
	}

	enqueue_create_notification(shared_by, notification_doc)