Example #1
0
    def set_value(self, dt, dn, field, val, modified=None, modified_by=None):
        from webnotes.utils import now
        if dn and dt != dn:
            self.sql(
                """update `tab%s` set `%s`=%s, modified=%s, modified_by=%s
				where name=%s""" % (dt, field, "%s", "%s", "%s", "%s"),
                (val, modified or now(), modified_by
                 or webnotes.session["user"], dn))
        else:
            if self.sql(
                    "select value from tabSingles where field=%s and doctype=%s",
                (field, dt)):
                self.sql(
                    """update tabSingles set value=%s where field=%s and doctype=%s""",
                    (val, field, dt))
            else:
                self.sql(
                    """insert into tabSingles(doctype, field, value) 
					values (%s, %s, %s)""", (
                        dt,
                        field,
                        val,
                    ))

            if field != "modified":
                self.set_value(dt, dn, "modified", modified or now())
Example #2
0
def remove_against_link_from_jv(ref_type, ref_no, against_field):
    linked_jv = webnotes.conn.sql_list(
        """select parent from `tabJournal Voucher Detail` 
		where `%s`=%s and docstatus < 2""" % (against_field, "%s"), (ref_no))

    if linked_jv:
        webnotes.conn.sql(
            """update `tabJournal Voucher Detail` set `%s`=null,
			modified=%s, modified_by=%s
			where `%s`=%s and docstatus < 2""" %
            (against_field, "%s", "%s", against_field, "%s"),
            (now(), webnotes.session.user, ref_no))

        webnotes.conn.sql(
            """update `tabGL Entry`
			set against_voucher_type=null, against_voucher=null,
			modified=%s, modified_by=%s
			where against_voucher_type=%s and against_voucher=%s
			and voucher_no != ifnull(against_voucher, '')""",
            (now(), webnotes.session.user, ref_type, ref_no))

        webnotes.msgprint("{msg} {linked_jv}".format(
            msg=_("""Following linked Journal Vouchers \
			made against this transaction has been unlinked. You can link them again with other \
			transactions via Payment Reconciliation Tool."""),
            linked_jv="\n".join(linked_jv)))
Example #3
0
	def update_status(self):
		status = webnotes.conn.get_value("Support Ticket", self.doc.name, "status")
		if self.doc.status!="Open" and status =="Open" and not self.doc.first_responded_on:
			self.doc.first_responded_on = now()
		if self.doc.status=="Closed" and status !="Closed":
			self.doc.resolution_date = now()
		if self.doc.status=="Open" and status !="Open":
			self.doc.resolution_date = ""
	def update_status(self):
		status = webnotes.conn.get_value("Support Ticket", self.doc.name, "status")
		if self.doc.status!="Open" and status =="Open" and not self.doc.first_responded_on:
			self.doc.first_responded_on = now()
		if self.doc.status=="Closed" and status !="Closed":
			self.doc.resolution_date = now()
		if self.doc.status=="Open" and status !="Open":
			self.doc.resolution_date = ""
Example #5
0
def backup(site=None, with_files=False, verbose=True, backup_path_db=None, backup_path_files=None):
	from webnotes.utils.backups import scheduled_backup
	webnotes.connect(site=site)
	odb = scheduled_backup(ignore_files=not with_files, backup_path_db=backup_path_db, backup_path_files=backup_path_files)
	if verbose:
		from webnotes.utils import now
		print "database backup taken -", odb.backup_path_db, "- on", now()
		if with_files:
			print "files backup taken -", odb.backup_path_files, "- on", now()
	webnotes.destroy()
	return odb
Example #6
0
def backup(site=None, with_files=False, verbose=True, backup_path_db=None, backup_path_files=None):
	from webnotes.utils.backups import scheduled_backup
	webnotes.connect(site=site)
	odb = scheduled_backup(ignore_files=not with_files, backup_path_db=backup_path_db, backup_path_files=backup_path_files)
	if verbose:
		from webnotes.utils import now
		print "database backup taken -", odb.backup_path_db, "- on", now()
		if with_files:
			print "files backup taken -", odb.backup_path_files, "- on", now()
	webnotes.destroy()
	return odb
Example #7
0
def remove_against_link_from_jv(ref_type, ref_no, against_field):
	webnotes.conn.sql("""update `tabJournal Voucher Detail` set `%s`=null,
		modified=%s, modified_by=%s
		where `%s`=%s and docstatus < 2""" % (against_field, "%s", "%s", against_field, "%s"), 
		(now(), webnotes.session.user, ref_no))
	
	webnotes.conn.sql("""update `tabGL Entry`
		set against_voucher_type=null, against_voucher=null,
		modified=%s, modified_by=%s
		where against_voucher_type=%s and against_voucher=%s
		and voucher_no != ifnull(against_voucher, '')""",
		(now(), webnotes.session.user, ref_type, ref_no))
Example #8
0
def remove_against_link_from_jv(ref_type, ref_no, against_field):
	webnotes.conn.sql("""update `tabJournal Voucher Detail` set `%s`=null,
		modified=%s, modified_by=%s
		where `%s`=%s and docstatus < 2""" % (against_field, "%s", "%s", against_field, "%s"), 
		(now(), webnotes.session.user, ref_no))
	
	webnotes.conn.sql("""update `tabGL Entry`
		set against_voucher_type=null, against_voucher=null,
		modified=%s, modified_by=%s
		where against_voucher_type=%s and against_voucher=%s
		and voucher_no != ifnull(against_voucher, "")
		and ifnull(is_cancelled, "No")="No" """,
		(now(), webnotes.session.user, ref_type, ref_no))
Example #9
0
def send_message(subject="Website Query", message="", sender="", status="Open"):
    if not message:
        webnotes.response["message"] = "Please write something"
        return

    if not sender:
        webnotes.response["message"] = "Email Id Required"
        return

        # make lead / communication
    from selling.doctype.lead.get_leads import add_sales_communication

    add_sales_communication(subject or "Website Query", message, sender, sender, mail=None, status=status)

    # guest method, cap max writes per hour
    if (
        webnotes.conn.sql(
            """select count(*) from `tabCommunication`
		where TIMEDIFF(%s, modified) < '01:00:00'""",
            now(),
        )[0][0]
        > max_communications_per_hour
    ):
        webnotes.response[
            "message"
        ] = "Sorry: we believe we have received an unreasonably high number of requests of this kind. Please try later"
        return

    webnotes.response["message"] = "Thank You"
Example #10
0
def send_message(subject="Website Query", message="", sender=""):
    if not message:
        webnotes.response["message"] = "Please write something"
        return

    if not sender:
        webnotes.response["message"] = "Email Id Required"
        return

        # guest method, cap max writes per hour
    if (
        webnotes.conn.sql(
            """select count(*) from `tabCommunication`
		where TIMEDIFF(%s, modified) < '01:00:00'""",
            now(),
        )[0][0]
        > max_communications_per_hour
    ):
        webnotes.response[
            "message"
        ] = "Sorry: we believe we have received an unreasonably high number of requests of this kind. Please try later"
        return

        # send email
    forward_to_email = webnotes.conn.get_value("Contact Us Settings", None, "forward_to_email")
    if forward_to_email:
        from webnotes.utils.email_lib import sendmail

        sendmail(forward_to_email, sender, message, subject)

    webnotes.response.status = "okay"

    return True
Example #11
0
def update_user_limit(site_name , max_users, _type='POST'):
	from webnotes.model.doc import Document
	from webnotes.utils import now
	site_name = get_site_name(site_name)
	site_details = webnotes.conn.sql("select database_name, database_password from `tabSite Details` where name = '%s'"%(site_name))
	
	if site_details:
		import MySQLdb
		try:
			myDB = MySQLdb.connect(user="******"%site_details[0][0], passwd="%s"%site_details[0][1], db="%s"%site_details[0][0])
			cHandler = myDB.cursor()
			cHandler.execute("update  tabSingles set value = '%s' where field='max_users' and doctype = 'Global Defaults'"%max_users)
			cHandler.execute("commit")
			myDB.close()

			d = Document("Site Log")
			d.site_name =site_name
			d.date_time = now()
			d.purpose = 'Max User Setting'
			d.max_users = max_users
			d.save()
			webnotes.conn.sql("commit")
			return {"status":"200", 'name':d.name}

		except Exception as inst: 
			return {"status":"417", "error":inst}
Example #12
0
	def update_packed_qty(self, event=''):
		"""
			Updates packed qty for all items
		"""
		if event not in ['submit', 'cancel']:
			raise Exception('update_packed_quantity can only be called on submit or cancel')

		# Get Delivery Note Items, Item Quantity Dict and No. of Cases for this Packing slip
		dn_details, ps_item_qty, no_of_cases = self.get_details_for_packing()

		for item in dn_details:
			new_packed_qty = flt(item['packed_qty'])
			if (new_packed_qty < 0) or (new_packed_qty > flt(item['qty'])):
				webnotes.msgprint("Invalid new packed quantity for item %s. \
					Please try again or contact [email protected]" % item['item_code'], raise_exception=1)
			
			delivery_note_item = webnotes.conn.get_value("Delivery Note Item", {
				"parent": self.doc.delivery_note, "item_code": item["item_code"]})
			
			webnotes.conn.sql("""\
				UPDATE `tabDelivery Note Item`
				SET packed_qty = %s
				WHERE parent = %s AND item_code = %s""",
				(new_packed_qty, self.doc.delivery_note, item['item_code']))
			webnotes.conn.set_value("Delivery Note", self.doc.delivery_note,
				"modified", now())
  def create_production_order(self,company, fy, pp_detail = '', pro_detail = ''):
    pro_lbl = {'production_item': 0, 'description': 1, 'qty' : 2, 'stock_uom' : 3, 'bom_no': 4, 'consider_sa_items': 5}
           
    default_values = { 'transaction_date'            : now(),
                       'origin'          : pp_detail and 'MRP' or 'Direct',
                       'wip_warehouse'   : 'MB1-Stores',
                       'status'          : 'Draft',
                       'company'         : company,
                       'fiscal_year'     : fy }
     
    pro_list, count = pp_detail and pp_detail or pro_detail, 0

    while (count < len(pro_list)):
      pro_doc = Document('Production Order')

      for key in pro_lbl.keys():
        pro_doc.fields[key] = pro_list[count][pro_lbl[key]]
      
      for key in default_values:
        pro_doc.fields[key] = default_values[key]
      
      pro_doc.save(new = 1)
      pro_list[count] = pro_doc.name
      
      # This was for adding raw materials in pro detail and get sa items
      #sa_list = get_obj('Porduction Order', pro_doc.name, with_children = 1).get_purchase_item( get_sa_items = 1, add_child= 1)
      #for sa_item in sa_list:
      #  pro_list.append(sa_item)

      count = count + 1
    return pro_list
Example #14
0
def sign_up(email, full_name):
    profile = webnotes.conn.get("Profile", {"email": email})
    if profile:
        if profile.disabled:
            return _("Registered but disabled.")
        else:
            return _("Already Registered")
    else:
        if (
            webnotes.conn.sql(
                """select count(*) from tabProfile where 
			TIMEDIFF(%s, modified) > '1:00:00' """,
                now(),
            )[0][0]
            > 200
        ):
            raise Exception, "Too Many New Profiles"
        from webnotes.utils import random_string

        profile = webnotes.bean(
            {
                "doctype": "Profile",
                "email": email,
                "first_name": full_name,
                "enabled": 1,
                "new_password": random_string(10),
                "user_type": "Website User",
            }
        )
        profile.ignore_permissions = True
        profile.insert()
        return _("Registration Details Emailed.")
Example #15
0
	def __init__(self, content):
		import email, email.utils
		import datetime
		# print 'content start'
		# print content
		# print 'content end'
		self.mail = email.message_from_string(content)
		
		self.text_content = ''
		self.html_content = ''
		self.attachments = []	
		self.parse()
		self.set_content_and_type()
		self.set_subject()

		self.from_email = extract_email_id(self.mail["From"])
		self.from_real_name = email.utils.parseaddr(self.mail["From"])[0]
		
		if self.mail["Date"]:
			utc = time.mktime(email.utils.parsedate(self.mail["Date"]))
			utc_dt = datetime.datetime.utcfromtimestamp(utc)
			self.date = convert_utc_to_user_timezone(utc_dt).strftime('%Y-%m-%d %H:%M:%S')
			
		else:
			self.date = now()
Example #16
0
def rebuild_node(doctype, parent, left, parent_field, cnt=0):
    """
		reset lft, rgt and recursive call for all children
	"""
    from webnotes.utils import now
    n = now()

    # the right value of this node is the left value + 1
    right = left + 1

    # get all children of this node
    result = webnotes.conn.sql("SELECT name FROM `tab%s` WHERE `%s`='%s'" %
                               (doctype, parent_field, parent))
    for r in result:
        right = rebuild_node(doctype, r[0], right, parent_field, cnt)

    # we've got the left value, and now that we've processed
    # the children of this node we also know the right value
    webnotes.conn.sql(
        "UPDATE `tab%s` SET lft=%s, rgt=%s, modified='%s' WHERE name='%s'" %
        (doctype, left, right, n, parent))

    # commit after every 100
    cnt += 1
    if cnt % 100 == 0:
        cnt = 0
        webnotes.conn.sql("commit")
        webnotes.conn.sql("start transaction")

    #return the right value of this node + 1
    return right + 1
Example #17
0
	def set_value(self, dt, dn, field, val, modified=None, modified_by=None):
		from webnotes.utils import now
		if dn and dt!=dn:
			self.sql("""update `tab%s` set `%s`=%s, modified=%s, modified_by=%s
				where name=%s""" % (dt, field, "%s", "%s", "%s", "%s"),
				(val, modified or now(), modified_by or webnotes.session["user"], dn))
		else:
			if self.sql("select value from tabSingles where field=%s and doctype=%s", (field, dt)):
				self.sql("""update tabSingles set value=%s where field=%s and doctype=%s""", 
					(val, field, dt))
			else:
				self.sql("""insert into tabSingles(doctype, field, value) 
					values (%s, %s, %s)""", (dt, field, val, ))
					
			if field!="modified":
				self.set_value(dt, dn, "modified", modified or now())
Example #18
0
    def update_packed_qty(self, event=''):
        """
			Updates packed qty for all items
		"""
        if event not in ['submit', 'cancel']:
            raise Exception(
                'update_packed_quantity can only be called on submit or cancel'
            )

        # Get Delivery Note Items, Item Quantity Dict and No. of Cases for this Packing slip
        dn_details, ps_item_qty, no_of_cases = self.get_details_for_packing()

        for item in dn_details:
            new_packed_qty = flt(item['packed_qty'])
            if (new_packed_qty < 0) or (new_packed_qty > flt(item['qty'])):
                webnotes.msgprint("Invalid new packed quantity for item %s. \
					Please try again or contact [email protected]" % item['item_code'],
                                  raise_exception=1)

            webnotes.conn.sql(
                """\
				UPDATE `tabDelivery Note Item`
				SET packed_qty = %s
				WHERE parent = %s AND item_code = %s""",
                (new_packed_qty, self.doc.delivery_note, item['item_code']))
            webnotes.conn.set_value("Delivery Note", self.doc.delivery_note,
                                    "modified", now())
Example #19
0
def sign_up(email, full_name):
    profile = webnotes.conn.get("Profile", {"email": email})
    if profile:
        if profile.disabled:
            return _("Registered but disabled.")
        else:
            return _("Already Registered")
    else:
        if webnotes.conn.sql(
                """select count(*) from tabProfile where 
			TIMEDIFF(%s, modified) > '1:00:00' """, now())[0][0] > 200:
            raise Exception, "Too Many New Profiles"
        from webnotes.utils import random_string
        profile = webnotes.bean({
            "doctype": "Profile",
            "email": email,
            "first_name": full_name,
            "enabled": 1,
            "new_password": random_string(10),
            "user_type": "Website User",
            "send_invite_email": 1
        })
        profile.ignore_permissions = True
        profile.insert()
        return _("Registration Details Emailed.")
Example #20
0
    def get_valuation_rate(self, args):
        """ Get average valuation rate of relevant warehouses 
			as per valuation method (MAR/FIFO) 
			as on costing date	
		"""
        from stock.utils import get_incoming_rate
        dt = self.doc.costing_date or nowdate()
        time = self.doc.costing_date == nowdate() and now().split(
        )[1] or '23:59'
        warehouse = webnotes.conn.sql(
            "select warehouse from `tabBin` where item_code = %s",
            args['item_code'])
        rate = []
        for wh in warehouse:
            r = get_incoming_rate({
                "item_code": args.get("item_code"),
                "warehouse": wh[0],
                "posting_date": dt,
                "posting_time": time,
                "qty": args.get("qty") or 0
            })
            if r:
                rate.append(r)

        return rate and flt(sum(rate)) / len(rate) or 0
Example #21
0
 def change_modified_of_parent(self):
     parent_list = sql(
         'SELECT parent from tabDocField where fieldtype="Table" and options="%s"'
         % self.doc.name)
     for p in parent_list:
         sql('UPDATE tabDocType SET modified="%s" WHERE `name`="%s"' %
             (now(), p[0]))
Example #22
0
def activate_deactivate(site_name , is_active, _type='POST'):
	# return "hi"
	from webnotes.model.doc import Document
	from webnotes.utils import now
	site_details = webnotes.conn.sql("select database_name, database_password from `tabSite Details` where name = '%s'"%(site_name))
	# return site_details
	if site_details:
		import MySQLdb
		try:
			myDB = MySQLdb.connect(user="******"%site_details[0][0], passwd="%s"%site_details[0][1], db="%s"%site_details[0][0])
			cHandler = myDB.cursor()
			cHandler.execute("update  tabSingles set value = '%s' where field='is_active' and doctype = 'Global Defaults'"%is_active)
			cHandler.execute("commit")
			myDB.close()

			d = Document("Site Log")
			d.site_name =site_name
			d.is_active = is_active
			d.date_time = now()
			d.save()
			webnotes.conn.sql("commit")
			return {"status":"200", 'name':d.name}

		except Exception as inst: 
			return {"status":"417", "error":inst}
	else:
		return{"status":"404", "Error":"Site Not Fount"}
Example #23
0
 def set(self, doc, field, val):
     from webnotes.utils import now
     doc.modified = now()
     doc.modified_by = webnotes.session["user"]
     self.set_value(doc.doctype, doc.name, field, val, doc.modified,
                    doc.modified_by)
     doc.fields[field] = val
Example #24
0
def update_add_node(doctype, name, parent, parent_field):
	"""
		insert a new node
	"""
	from webnotes.utils import now
	n = now()

	# get the last sibling of the parent
	if parent:
		right = webnotes.conn.sql("select rgt from `tab%s` where name='%s'" % (doctype, parent))[0][0]
	else: # root
		right = webnotes.conn.sql("select ifnull(max(rgt),0)+1 from `tab%s` where ifnull(`%s`,'') =''" % (doctype, parent_field))[0][0]
	right = right or 1
		
	# update all on the right
	webnotes.conn.sql("update `tab%s` set rgt = rgt+2, modified='%s' where rgt >= %s" %(doctype,n,right))
	webnotes.conn.sql("update `tab%s` set lft = lft+2, modified='%s' where lft >= %s" %(doctype,n,right))
	
	# update index of new node
	if webnotes.conn.sql("select * from `tab%s` where lft=%s or rgt=%s"% (doctype, right, right+1)):
		webnotes.msgprint("Nested set error. Please send mail to support")
		raise Exception

	webnotes.conn.sql("update `tab%s` set lft=%s, rgt=%s, modified='%s' where name='%s'" % (doctype,right,right+1,n,name))
	return right
Example #25
0
def rebuild_node(doctype, parent, left, parent_field, cnt = 0):
	"""
		reset lft, rgt and recursive call for all children
	"""
	from webnotes.utils import now
	n = now()
	
	# the right value of this node is the left value + 1
	right = left+1	

	# get all children of this node
	result = webnotes.conn.sql("SELECT name FROM `tab%s` WHERE `%s`='%s'" % (doctype, parent_field, parent))
	for r in result:
		right = rebuild_node(doctype, r[0], right, parent_field, cnt)

	# we've got the left value, and now that we've processed
	# the children of this node we also know the right value
	webnotes.conn.sql("UPDATE `tab%s` SET lft=%s, rgt=%s, modified='%s' WHERE name='%s'" % (doctype,left,right,n,parent))

	# commit after every 100
	cnt += 1
	if cnt % 100 == 0:
		cnt = 0
		webnotes.conn.sql("commit")
		webnotes.conn.sql("start transaction")

	#return the right value of this node + 1
	return right+1
Example #26
0
def update_add_node(doctype, name, parent, parent_field):
    """
		insert a new node
	"""
    from webnotes.utils import now
    n = now()

    # get the last sibling of the parent
    if parent:
        right = webnotes.conn.sql("select rgt from `tab%s` where name='%s'" %
                                  (doctype, parent))[0][0]
    else:  # root
        right = webnotes.conn.sql(
            "select ifnull(max(rgt),0)+1 from `tab%s` where ifnull(`%s`,'') =''"
            % (doctype, parent_field))[0][0]
    right = right or 1

    # update all on the right
    webnotes.conn.sql(
        "update `tab%s` set rgt = rgt+2, modified='%s' where rgt >= %s" %
        (doctype, n, right))
    webnotes.conn.sql(
        "update `tab%s` set lft = lft+2, modified='%s' where lft >= %s" %
        (doctype, n, right))

    # update index of new node
    if webnotes.conn.sql("select * from `tab%s` where lft=%s or rgt=%s" %
                         (doctype, right, right + 1)):
        webnotes.msgprint("Nested set error. Please send mail to support")
        raise Exception

    webnotes.conn.sql(
        "update `tab%s` set lft=%s, rgt=%s, modified='%s' where name='%s'" %
        (doctype, right, right + 1, n, name))
    return right
Example #27
0
 def update_production_order(self, is_submit):
     if self.doc.production_order:
         pro_obj = get_obj("Production Order", self.doc.production_order)
         if flt(pro_obj.doc.docstatus) != 1:
             msgprint(
                 "You cannot do any transaction against Production Order : %s, as it's not submitted"
                 % (pro_obj.doc.name))
             raise Exception
         if pro_obj.doc.status == 'Stopped':
             msgprint(
                 "You cannot do any transaction against Production Order : %s, as it's status is 'Stopped'"
                 % (pro_obj.doc.name))
             raise Exception
         if getdate(pro_obj.doc.posting_date) > getdate(
                 self.doc.posting_date):
             msgprint(
                 "Posting Date of Stock Entry cannot be before Posting Date of Production Order "
                 + cstr(self.doc.production_order))
             raise Exception
         if self.doc.process == 'Backflush':
             pro_obj.doc.produced_qty = flt(pro_obj.doc.produced_qty) + (
                 is_submit and 1 or -1) * flt(self.doc.fg_completed_qty)
             get_obj('Warehouse', pro_obj.doc.fg_warehouse).update_bin(
                 0, 0, 0, 0,
                 (is_submit and 1 or -1) * flt(self.doc.fg_completed_qty),
                 pro_obj.doc.production_item, now())
         pro_obj.doc.status = (flt(pro_obj.doc.qty) == flt(
             pro_obj.doc.produced_qty)) and 'Completed' or 'In Process'
         pro_obj.doc.save()
Example #28
0
def send_message(subject="Website Query",
                 message="",
                 sender="",
                 status="Open"):
    if not message:
        webnotes.response["message"] = 'Please write something'
        return

    if not sender:
        webnotes.response["message"] = 'Email Id Required'
        return

    # make lead / communication
    from selling.doctype.lead.get_leads import add_sales_communication
    add_sales_communication(subject or "Website Query",
                            message,
                            sender,
                            sender,
                            mail=None,
                            status=status)

    # guest method, cap max writes per hour
    if webnotes.conn.sql(
            """select count(*) from `tabCommunication`
		where TIMEDIFF(%s, modified) < '01:00:00'""",
            now())[0][0] > max_communications_per_hour:
        webnotes.response[
            "message"] = "Sorry: we believe we have received an unreasonably high number of requests of this kind. Please try later"
        return

    webnotes.response["message"] = 'Thank You'
Example #29
0
def send_message(subject="Website Query", message="", sender=""):
    if not message:
        webnotes.response["message"] = 'Please write something'
        return

    if not sender:
        webnotes.response["message"] = 'Email Id Required'
        return

    # guest method, cap max writes per hour
    if webnotes.conn.sql(
            """select count(*) from `tabCommunication`
		where TIMEDIFF(%s, modified) < '01:00:00'""",
            now())[0][0] > max_communications_per_hour:
        webnotes.response[
            "message"] = "Sorry: we believe we have received an unreasonably high number of requests of this kind. Please try later"
        return

    # send email
    forward_to_email = webnotes.conn.get_value("Contact Us Settings", None,
                                               "forward_to_email")
    if forward_to_email:
        from webnotes.utils.email_lib import sendmail
        sendmail(forward_to_email, sender, message, subject)

    webnotes.response.status = "okay"

    return True
Example #30
0
	def update_stock(self, values, is_amended = 'No'):
		for v in values:
			sle_id, valid_serial_nos = '', ''
			# get serial nos
			if v.get("serial_no", "").strip():
				valid_serial_nos = get_valid_serial_nos(v["serial_no"], 
					v['actual_qty'], v['item_code'])
				v["serial_no"] = valid_serial_nos and "\n".join(valid_serial_nos) or ""
			
			# reverse quantities for cancel
			if v.get('is_cancelled') == 'Yes':
				v['actual_qty'] = -flt(v['actual_qty'])
				# cancel matching entry
				webnotes.conn.sql("""update `tabStock Ledger Entry` set is_cancelled='Yes',
					modified=%s, modified_by=%s
					where voucher_no=%s and voucher_type=%s""", 
					(now(), webnotes.session.user, v['voucher_no'], v['voucher_type']))

			if v.get("actual_qty"):
				sle_id = self.make_entry(v)
				
			args = v.copy()
			args.update({
				"sle_id": sle_id,
				"is_amended": is_amended
			})
			
			get_obj('Warehouse', v["warehouse"]).update_bin(args)
Example #31
0
def set_as_cancel(voucher_type, voucher_no):
    webnotes.conn.sql(
        """update `tabGL Entry` set is_cancelled='Yes',
		modified=%s, modified_by=%s
		where voucher_type=%s and voucher_no=%s""",
        (now(), webnotes.session.user, voucher_type, voucher_no),
    )
Example #32
0
def get_context():
	"""generate rss feed"""
		
	host = get_request_site_address()
	
	blog_list = webnotes.conn.sql("""\
		select page_name as name, published_on, modified, title, content from `tabBlog Post` 
		where ifnull(published,0)=1
		order by published_on desc limit 20""", as_dict=1)

	for blog in blog_list:
		blog.link = urllib.quote(host + '/' + blog.name + '.html')
		blog.content = escape_html(blog.content or "")
	
	if blog_list:
		modified = max((blog['modified'] for blog in blog_list))
	else:
		modified = now()

	ws = webnotes.doc('Website Settings', 'Website Settings')

	context = {
		'title': ws.title_prefix,
		'description': ws.description or ((ws.title_prefix or "") + ' Blog'),
		'modified': modified,
		'items': blog_list,
		'link': host + '/blog'
	}
	
	webnotes.response.content_type = "text/xml"
	
	# print context
	return context
	
Example #33
0
def scheduled_backup(older_than=6, ignore_files=False):
	"""this function is called from scheduler
		deletes backups older than 7 days
		takes backup"""
	odb = new_backup(older_than, ignore_files)
	
	from webnotes.utils import now
	print "backup taken -", odb.backup_path_db, "- on", now()
Example #34
0
	def change_modified_of_parent(self):
		if webnotes.in_import:
			return
		parent_list = webnotes.conn.sql("""SELECT parent 
			from tabDocField where fieldtype="Table" and options="%s" """ % self.doc.name)
		for p in parent_list:
			webnotes.conn.sql('''UPDATE tabDocType SET modified="%s" 
				WHERE `name`="%s"''' % (now(), p[0]))
Example #35
0
 def on_submit(self):
     set(self.doc, 'status', 'Submitted')
     # increase Planned Qty of Prooduction Item by Qty
     get_obj('Warehouse',
             self.doc.fg_warehouse).update_bin(0, 0, 0, 0,
                                               flt(self.doc.qty),
                                               self.doc.production_item,
                                               now())
Example #36
0
 def restore_records(self, arg):
     arg = eval(arg)
     for k in arg:
         for r in arg[k]:
             sql("update `tab%s` set docstatus = 0, modified = '%s', trash_reason = '' where name = '%s'"
                 % (k, now(), r))
             dt_obj = get_obj(k, r)
             if hasattr(dt_obj, 'on_restore'): dt_obj.on_restore()
def scheduled_backup(older_than=6, ignore_files=False):
	"""this function is called from scheduler
		deletes backups older than 7 days
		takes backup"""
	odb = new_backup(older_than, ignore_files)
	
	from webnotes.utils import now
	print "backup taken -", odb.backup_path_db, "- on", now()
Example #38
0
def update_followers(dt=None, dn=None, subject=None, update_by=None, doc=None):
    "Updates the timestamp and subject in follower table (for feed generation)"
    from webnotes.utils import now
    webnotes.conn.sql("update tabFollower set modified=%s, subject=%s, modified_by=%s where doc_type=%s and doc_name=%s", \
     (now(),
     subject or doc.fields.get('subject'), \
     update_by or webnotes.session['user'],\
     dt or doc.doctype,
     dn or doc.name))
Example #39
0
    def change_modified_of_parent(self):
        if webnotes.in_import:
            return
        parent_list = webnotes.conn.sql("""SELECT parent 
			from tabDocField where fieldtype="Table" and options="%s" """ %
                                        self.doc.name)
        for p in parent_list:
            webnotes.conn.sql('''UPDATE tabDocType SET modified="%s" 
				WHERE `name`="%s"''' % (now(), p[0]))
Example #40
0
def update_followers(dt=None, dn=None, subject=None, update_by=None, doc=None):
	"Updates the timestamp and subject in follower table (for feed generation)"
	from webnotes.utils import now
	webnotes.conn.sql("update tabFollower set modified=%s, subject=%s, modified_by=%s where doc_type=%s and doc_name=%s", \
		(now(), 
		subject or doc.fields.get('subject'), \
		update_by or webnotes.session['user'],\
		dt or doc.doctype, 
		dn or doc.name))
Example #41
0
    def calculate_cost(self):
        """Calculate bom totals"""
        self.doc.costing_date = nowdate()
        self.calculate_op_cost()
        self.calculate_rm_cost()
        self.doc.total_cost = self.doc.raw_material_cost + self.doc.operating_cost
        self.doc.modified = now()
        self.doc.save()

        self.update_flat_bom_engine(is_submit=self.doc.docstatus)
Example #42
0
	def reset_password(self):
		"""reset password"""
		from webnotes.utils import random_string, now
		pwd = random_string(8)
		
		# update tab Profile
		webnotes.conn.sql("""UPDATE tabProfile SET password=password(%s), modified=%s 
			WHERE name=%s""", (pwd, now(), self.name))

		return pwd
Example #43
0
    def calculate_cost(self):
        """Calculate bom totals"""
        self.doc.costing_date = nowdate()
        self.calculate_op_cost()
        self.calculate_rm_cost()
        self.doc.total_cost = self.doc.raw_material_cost + self.doc.operating_cost
        self.doc.modified = now()
        self.doc.save()

        self.update_flat_bom_engine(is_submit=self.doc.docstatus)
Example #44
0
def add_answer(arg):
	arg = load_json(arg)
	
	from webnotes.model.doc import Document
	a = Document('Answer')
	a.answer = arg['answer']
	a.question = arg['qid']
	a.points = 1
	a.save(1)
	
	webnotes.conn.set_value('Question', arg['qid'], 'modified', now())
Example #45
0
def scheduled_backup():
	"""this function is called from scheduler
		deletes backups older than 7 days
		takes backup"""
	delete_temp_backups(older_than=168)
	odb = BackupGenerator(webnotes.conn.cur_db_name, webnotes.conn.cur_db_name,\
						  webnotes.get_db_password(webnotes.conn.cur_db_name))
	odb.get_backup()
	
	from webnotes.utils import now
	print "backup taken -", odb.backup_path_db, "- on", now()
Example #46
0
 def stop_unstop(self, status):
     """ Called from client side on Stop/Unstop event"""
     self.update_status(status)
     # Update Planned Qty of Production Item
     qty = (flt(self.doc.qty) - flt(self.doc.produced_qty)) * (
         (status == 'Stopped') and -1 or 1)
     get_obj('Warehouse',
             self.doc.fg_warehouse).update_bin(0, 0, 0, 0, flt(qty),
                                               self.doc.production_item,
                                               now())
     msgprint("Production Order has been %s" % status)
Example #47
0
def scheduled_backup(older_than=6):
	"""this function is called from scheduler
		deletes backups older than 7 days
		takes backup"""
	delete_temp_backups(older_than=168)
	odb = BackupGenerator(webnotes.conn.cur_db_name, webnotes.conn.cur_db_name,\
						  webnotes.get_db_password(webnotes.conn.cur_db_name))
	odb.get_backup(older_than)
	
	from webnotes.utils import now
	print "backup taken -", odb.backup_path_db, "- on", now()
Example #48
0
def add_answer(arg):
    arg = load_json(arg)

    from webnotes.model.doc import Document
    a = Document('Answer')
    a.answer = arg['answer']
    a.question = arg['qid']
    a.points = 1
    a.save(1)

    webnotes.conn.set_value('Question', arg['qid'], 'modified', now())
Example #49
0
def remove_against_link_from_jv(ref_type, ref_no, against_field):
	linked_jv = webnotes.conn.sql_list("""select parent from `tabJournal Voucher Detail` 
		where `%s`=%s and docstatus < 2""" % (against_field, "%s"), (ref_no))
		
	if linked_jv:	
		webnotes.conn.sql("""update `tabJournal Voucher Detail` set `%s`=null,
			modified=%s, modified_by=%s
			where `%s`=%s and docstatus < 2""" % (against_field, "%s", "%s", against_field, "%s"), 
			(now(), webnotes.session.user, ref_no))
	
		webnotes.conn.sql("""update `tabGL Entry`
			set against_voucher_type=null, against_voucher=null,
			modified=%s, modified_by=%s
			where against_voucher_type=%s and against_voucher=%s
			and voucher_no != ifnull(against_voucher, '')""",
			(now(), webnotes.session.user, ref_type, ref_no))
			
		webnotes.msgprint("{msg} {linked_jv}".format(msg = _("""Following linked Journal Vouchers \
			made against this transaction has been unlinked. You can link them again with other \
			transactions via Payment Reconciliation Tool."""), linked_jv="\n".join(linked_jv)))
Example #50
0
    def update_permissions(self, args=''):
        args = eval(args)
        di = args['perm_dict']
        doctype_keys = di.keys()  # ['Opportunity','Competitor','Zone','State']
        for parent in doctype_keys:
            for permlevel in di[parent].keys():
                for role in di[parent][permlevel].keys():

                    if role:

                        # check if Permissions for that perm level and Role exists
                        exists = sql(
                            "select name from tabDocPerm where parent = %s and role = %s and ifnull(permlevel, 0) = %s",
                            (parent, role, cint(permlevel)))

                        # Get values of dictionary of Perm Level
                        pd = di[parent][permlevel][role]

                        # update
                        if exists and (1 in pd.values()):
                            sql(
                                "update tabDocPerm set `read` = %s, `write` = %s, `create` = %s, `submit` = %s, `cancel` = %s, `amend` = %s, `match`=%s where parent = %s and role = %s and permlevel = %s",
                                (pd['read'], pd['write'], pd['create'],
                                 pd['submit'], pd['cancel'], pd['amend'],
                                 pd.get('match'), parent, role, permlevel))

                        # new
                        elif not exists and (1 in pd.values()):

                            ch = Document('DocPerm')
                            ch.parentfield = 'permissions'
                            ch.parenttype = 'DocType'
                            ch.parent = parent
                            ch.role = role
                            ch.permlevel = cint(permlevel)
                            for key in pd.keys():
                                ch.fields[key] = pd.get(key, None)
                            ch.save(1)

                        # delete
                        elif exists and (1 not in pd.values()):
                            sql(
                                "delete from tabDocPerm where parent = %s and role = %s and ifnull(permlevel,0) = %s",
                                (parent, role, cint(permlevel)))

                        sql(
                            "update tabDocType set modified = %s where name = %s",
                            (now(), parent))

        from webnotes.utils.cache import CacheItem
        CacheItem(parent).clear()

        msgprint("Permissions Updated")
Example #51
0
	def update_timestamps_and_docstatus(self):
		from webnotes.utils import now
		ts = now()
		user = webnotes.__dict__.get('session', {}).get('user') or 'Administrator'

		for d in self.docs:
			if self.doc.fields.get('__islocal'):
				d.owner = user
				d.creation = ts

			d.modified_by = user
			d.modified = ts
			if d.docstatus != 2 and self.to_docstatus >= d.docstatus: # don't update deleted
				d.docstatus = self.to_docstatus
Example #52
0
 def update_field(self, df, new):
     import webnotes.model
     sql(
         "update tabDocField set idx = idx + 1, modified = %s where parent = %s and idx > %s",
         (now(), self.doc.dt, self.idx))
     for k in self.doc.fields:
         if k not in webnotes.model.default_fields and k not in self.ignore_fields and not k.startswith(
                 '_'):
             df.fields[k] = self.doc.fields[k]
     df.parent = self.doc.dt
     df.parenttype = 'DocType'
     df.parentfield = 'fields'
     df.idx = self.idx + 1
     df.save(new)
Example #53
0
    def update_timestamps_and_docstatus(self):
        from webnotes.utils import now
        ts = now()
        user = webnotes.__dict__.get('session',
                                     {}).get('user') or 'Administrator'

        for d in self.docs:
            if self.doc.fields.get('__islocal'):
                d.owner = user
                d.creation = ts

            d.modified_by = user
            d.modified = ts
            if d.docstatus != 2 and self.to_docstatus >= d.docstatus:  # don't update deleted
                d.docstatus = self.to_docstatus
Example #54
0
def update_remove_node(doctype, name):
	"""
		remove a node
	"""
	from webnotes.utils import now
	n = now()

	left = webnotes.conn.sql("select lft from `tab%s` where name='%s'" % (doctype,name))
	if left[0][0]:
		# reset this node
		webnotes.conn.sql("update `tab%s` set lft=0, rgt=0, modified='%s' where name='%s'" % (doctype,n,name))

		# update all on the right
		webnotes.conn.sql("update `tab%s` set rgt = rgt-2, modified='%s' where rgt > %s" %(doctype,n,left[0][0]))
		webnotes.conn.sql("update `tab%s` set lft = lft-2, modified='%s' where lft > %s" %(doctype,n,left[0][0]))
Example #55
0
	def get_valuation_rate(self, arg):
		""" Get average valuation rate of relevant warehouses 
			as per valuation method (MAR/FIFO) 
			as on costing date	
		"""

		dt = self.doc.costing_date or nowdate()
		time = self.doc.costing_date == nowdate() and now().split()[1] or '23:59'
		warehouse = sql("select warehouse from `tabBin` where item_code = %s", arg['item_code'])
		rate = []
		for wh in warehouse:
			r = get_obj('Valuation Control').get_incoming_rate(dt, time, arg['item_code'], wh[0], qty = arg.get('qty', 0))
			if r:
				rate.append(r)

		return rate and flt(sum(rate))/len(rate) or 0
Example #56
0
	def update_timestamps(self):
		"""
			Update owner, creation, modified_by, modified, docstatus
		"""
		from webnotes.utils import now
		ts = now()
		user = webnotes.__dict__.get('session', {}).get('user') or 'Administrator'
		
		for d in self.docs:
			if self.doc.__islocal:
				d.owner = user
				d.creation = ts
			
			d.modified_by = user
			d.modified = ts
			d.docstatus = self.to_docstatus
Example #57
0
	def add_permission(self,args=''):
		parent, role, level = eval(args)
		if sql("select name from tabDocPerm where parent=%s and role=%s and permlevel=%s", (parent, role, level)):
			msgprint("This permission rule already exists!")
			return
		
		d = Document('DocPerm')
		d.parent = parent
		d.parenttype = 'DocType'
		d.parentfield = 'permissions'
		d.role = role
		d.permlevel = cint(level)
		d.docstatus = 0
		d.save(1)
		
		sql("update tabDocType set modified = %s where name = %s",(now(), parent))
Example #58
0
    def get_valuation_rate(self, arg):
        """ Get average valuation rate of relevant warehouses 
			as per valuation method (MAR/FIFO) 
			as on costing date	
		"""

        dt = self.doc.costing_date or nowdate()
        time = self.doc.costing_date == nowdate() and now().split()[1] or "23:59"
        warehouse = sql("select warehouse from `tabBin` where item_code = %s", arg["item_code"])
        rate = []
        for wh in warehouse:
            r = get_obj("Valuation Control").get_incoming_rate(dt, time, arg["item_code"], wh[0], qty=arg.get("qty", 0))
            if r:
                rate.append(r)

        return rate and flt(sum(rate)) / len(rate) or 0