Esempio n. 1
0
	def process_message(self, mail):
		if mail.from_email == self.settings.email_id:
			return
			
		name = webnotes.conn.get_value("Job Applicant", {"email_id": mail.from_email}, 
			"name")
		if name:
			applicant = webnotes.model_wrapper("Job Applicant", name)
			if applicant.doc.status!="Rejected":
				applicant.doc.status = "Open"
			applicant.doc.save()
		else:
			name = (mail.from_real_name and (mail.from_real_name + " - ") or "") \
				+ mail.from_email
			applicant = webnotes.model_wrapper({
				"doctype":"Job Applicant",
				"applicant_name": name,
				"email_id": mail.from_email,
				"status": "Open"
			})
			applicant.insert()
		
		mail.save_attachments_in_doc(applicant.doc)
				
		make(content=mail.content, sender=mail.from_email, 
			doctype="Job Applicant", name=applicant.doc.name, set_lead=False)
Esempio n. 2
0
	def process_message(self, mail):
		if mail.from_email == self.email_settings.fields.get('support_email'):
			return
		thread_id = mail.get_thread_id()
		ticket = None

		if thread_id and webnotes.conn.exists("Support Ticket", thread_id):
			ticket = webnotes.model_wrapper("Support Ticket", thread_id)
			ticket.doc.status = 'Open'
			ticket.doc.save()
				
		else:
			ticket = webnotes.model_wrapper([{
				"doctype":"Support Ticket",
				"description": mail.content,
				"subject": mail.mail["Subject"],
				"raised_by": mail.from_email,
				"content_type": mail.content_type,
				"status": "Open"
			}])
			ticket.insert()

			if cint(self.email_settings.send_autoreply):
				if "mailer-daemon" not in mail.from_email.lower():
					self.send_auto_reply(ticket.doc)

		mail.save_attachments_in_doc(ticket.doc)
				
		make(content=mail.content, sender=mail.from_email, subject = ticket.doc.subject,
			doctype="Support Ticket", name=ticket.doc.name, 
			lead = ticket.doc.lead, contact=ticket.doc.contact, date=mail.date)
Esempio n. 3
0
	def on_update(self):
		"""clear web cache"""
		from website.utils import clear_cache
		clear_cache()
		
		if self.doc.default_product_category:
			webnotes.model_wrapper("Item Group", 
				self.doc.default_product_category).save()
Esempio n. 4
0
def add_node():
    # from webnotes.model.doc import Document
    ctype = webnotes.form_dict.get('ctype')
    parent_field = 'parent_' + ctype.lower().replace(' ', '_')
    name_field = ctype.lower().replace(' ', '_') + '_name'

    doclist = [{
        "doctype": ctype,
        "__islocal": 1,
        name_field: webnotes.form_dict['name_field'],
        parent_field: webnotes.form_dict['parent'],
        "is_group": webnotes.form_dict['is_group']
    }]
    webnotes.model_wrapper(doclist).save()
def move_remarks_to_comments():
	from webnotes.utils import get_fullname
	result = webnotes.conn.sql("""select name, remark, modified_by from `tabStock Reconciliation`
		where ifnull(remark, '')!=''""")
	fullname_map = {}
	for reco, remark, modified_by in result:
		webnotes.model_wrapper([{
			"doctype": "Comment",
			"comment": remark,
			"comment_by": modified_by,
			"comment_by_fullname": fullname_map.setdefault(modified_by, get_fullname(modified_by)),
			"comment_doctype": "Stock Reconciliation",
			"comment_docname": reco
		}]).insert()
Esempio n. 6
0
	def test_get_recipients_lead(self):
		w = webnotes.model_wrapper(test_records[0])
		w.insert()
		self.assertTrue("*****@*****.**" in w.controller.get_recipients())
		webnotes.conn.sql("""delete from `tabBulk Email`""")
		w.controller.send_emails()
		self.assertTrue(webnotes.conn.get_value("Bulk Email", {"recipient": "*****@*****.**"}))
Esempio n. 7
0
def execute():
    for name in webnotes.conn.sql("""select name from `tabHoliday List`"""):
        holiday_list_wrapper = webnotes.model_wrapper("Holiday List", name[0])

        desc_count = _count([
            d.description
            for d in holiday_list_wrapper.doclist.get({"doctype": "Holiday"})
        ])

        holiday_list_obj = webnotes.get_obj(
            doc=holiday_list_wrapper.doc, doclist=holiday_list_wrapper.doclist)

        save = False

        for desc in desc_count.keys():
            if desc in [
                    "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday",
                    "Friday", "Saturday"
            ] and desc_count[desc] > 50:
                holiday_list_obj.doclist = holiday_list_obj.doclist.get(
                    {"description": ["!=", desc]})

                webnotes.conn.sql(
                    """delete from `tabHoliday`
					where parent=%s and parenttype='Holiday List' 
					and `description`=%s""", (holiday_list_obj.doc.name, desc))
                holiday_list_obj.doc.weekly_off = desc
                holiday_list_obj.get_weekly_off_dates()
                save = True

        if save:
            holiday_list_wrapper.set_doclist(holiday_list_obj.doclist)
            holiday_list_wrapper.save()
Esempio n. 8
0
def manage_recurring_invoices():
	""" 
		Create recurring invoices on specific date by copying the original one
		and notify the concerned people
	"""
	recurring_invoices = webnotes.conn.sql("""select name, recurring_id
		from `tabSales Invoice` where ifnull(convert_into_recurring_invoice, 0)=1
		and docstatus=1 and next_date=%s
		and next_date <= ifnull(end_date, '2199-12-31')""", nowdate())
	
	exception_list = []
	for ref_invoice, recurring_id in recurring_invoices:
		if not webnotes.conn.sql("""select name from `tabSales Invoice`
				where posting_date=%s and recurring_id=%s and docstatus=1""",
				(nowdate(), recurring_id)):
			try:
				ref_wrapper = webnotes.model_wrapper('Sales Invoice', ref_invoice)
				new_invoice_wrapper = make_new_invoice(ref_wrapper)
				send_notification(new_invoice_wrapper)
				webnotes.conn.commit()
			except Exception, e:
				webnotes.conn.rollback()

				webnotes.conn.begin()
				webnotes.conn.sql("update `tabSales Invoice` set \
					convert_into_recurring_invoice = 0 where name = %s", ref_invoice)
				notify_errors(ref_invoice, ref_wrapper.doc.owner)
				webnotes.conn.commit()

				exception_list.append(webnotes.getTraceback())
			finally:
Esempio n. 9
0
def execute():
	for name in webnotes.conn.sql("""select name from `tabHoliday List`"""):
		holiday_list_wrapper = webnotes.model_wrapper("Holiday List", name[0])
		
		desc_count = _count([d.description for d in 
			holiday_list_wrapper.doclist.get({"doctype": "Holiday"})])
			
		holiday_list_obj = webnotes.get_obj(doc=holiday_list_wrapper.doc,
			doclist=holiday_list_wrapper.doclist)
			
		save = False
		
		for desc in desc_count.keys():
			if desc in ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday",
					"Friday", "Saturday"] and desc_count[desc] > 50:
				holiday_list_obj.doclist = holiday_list_obj.doclist.get(
					{"description": ["!=", desc]})
				
				webnotes.conn.sql("""delete from `tabHoliday`
					where parent=%s and parenttype='Holiday List' 
					and `description`=%s""", (holiday_list_obj.doc.name, desc))
				holiday_list_obj.doc.weekly_off = desc
				holiday_list_obj.get_weekly_off_dates()
				save = True
		
		if save:
			holiday_list_wrapper.set_doclist(holiday_list_obj.doclist)
			holiday_list_wrapper.save()
Esempio n. 10
0
def add_node():
    # from webnotes.model.doc import Document
    ctype = webnotes.form_dict.get("ctype")
    parent_field = "parent_" + ctype.lower().replace(" ", "_")
    name_field = ctype.lower().replace(" ", "_") + "_name"

    doclist = [
        {
            "doctype": ctype,
            "__islocal": 1,
            name_field: webnotes.form_dict["name_field"],
            parent_field: webnotes.form_dict["parent"],
            "is_group": webnotes.form_dict["is_group"],
        }
    ]
    webnotes.model_wrapper(doclist).save()
Esempio n. 11
0
	def test_purchase_invoice_calculation(self):
		test_doclist = [] + purchase_invoice_doclist
		for doc in test_doclist:
			if doc["doctype"] == "Purchase Taxes and Charges":
				del doc["tax_amount"]
				
		wrapper = webnotes.model_wrapper(test_doclist).insert()
		wrapper.load_from_db()
		
		# tax amounts
		expected_values = [
			["Shipping Charges - %s" % abbr, 100, 1350],
			["Customs Duty - %s" % abbr, 125, 1350],
			["Excise Duty - %s" % abbr, 140, 1490],
			["Education Cess - %s" % abbr, 2.8, 1492.8],
			["S&H Education Cess - %s" % abbr, 1.4, 1494.2],
			["CST - %s" % abbr, 29.88, 1524.08],
			["VAT - Test - %s" % abbr, 156.25, 1680.33],
			["Discount - %s" % abbr, 168.03, 1512.30],
		]
		
		for i, tax in enumerate(wrapper.doclist.get({"parentfield": "purchase_tax_details"})):
			self.assertEqual(tax.account_head, expected_values[i][0])
			self.assertEqual(tax.tax_amount, expected_values[i][1])
			self.assertEqual(tax.total, expected_values[i][2])

		expected_values = [
			["Home Desktop 100", 90],
			["Home Desktop 200", 135]
		]
		for i, item in enumerate(wrapper.doclist.get({"parentfield": "entries"})):
			self.assertEqual(item.item_code, expected_values[i][0])
			self.assertEqual(item.item_tax_amount, expected_values[i][1])
Esempio n. 12
0
def save_report():
	"""save report"""
	from webnotes.model.doc import Document
	
	data = webnotes.form_dict
	if webnotes.conn.exists('Report', data['name'].title()):
		d = Document('Report', data['name'].title())
	else:
		d = Document('Report')
		d.name = data['name']
		d.ref_doctype = data['doctype']
		
	d.json = data['json']
	webnotes.model_wrapper([d]).save()
	webnotes.msgprint("%s saved." % d.name)
	return d.name
Esempio n. 13
0
	def process_message(self, mail):
		name = self.get_existing_application(mail.from_email)
		if name:
			applicant = webnotes.model_wrapper("Job Applicant", name)
		else:
			applicant = webnotes.model_wrapper({
				"doctype":"Job Applicant",
				"applicant_name": mail.from_real_name or mail.from_email,
				"email_id": mail.from_email
			})
			applicant.insert()
		
		mail.save_attachments_in_doc(applicant.doc)
				
		make(content=mail.content, sender=mail.from_email, 
			doctype="Job Applicant", name=applicant.doc.name, set_lead=False)
Esempio n. 14
0
def get_slideshow(obj):
    slideshow = webnotes.model_wrapper("Website Slideshow", obj.doc.slideshow)
    obj.slides = slideshow.doclist.get({"doctype": "Website Slideshow Item"})
    obj.doc.slideshow_header = slideshow.doc.header or ""
    for s in obj.slides:
        if s.image and not s.image.lower().startswith("http"):
            s.image = "files/" + s.image
Esempio n. 15
0
	def add_cc(self,arg):
		cc = webnotes.model_wrapper(eval(arg))
		cc.doc.doctype = "Cost Center"
		cc.doc.old_parent = ""
		cc.insert()

		return cc.doc.name
Esempio n. 16
0
def get_slideshow(obj):
	slideshow = webnotes.model_wrapper("Website Slideshow", obj.doc.slideshow)
	obj.slides = slideshow.doclist.get({"doctype":"Website Slideshow Item"})
	obj.doc.slideshow_header = slideshow.doc.header or ""
	for s in obj.slides:
		if s.image and not s.image.lower().startswith("http"):
			s.image = "files/" + s.image
Esempio n. 17
0
	def test_gl_entries(self):
		wrapper = webnotes.model_wrapper(self.get_test_doclist())
		
		# circumvent the disabled calculation call
		obj = webnotes.get_obj(doc=wrapper.doc, doclist=wrapper.doclist)
		obj.calculate_taxes_and_totals()
		wrapper.set_doclist(obj.doclist)
		
		wrapper.insert()
		wrapper.submit()
		wrapper.load_from_db()
		dl = wrapper.doclist
		
		expected_gl_entries = {
			"_Test Supplier - _TC": [0, 1512.30],
			"_Test Account Cost for Goods Sold - _TC": [1250, 0],
			"_Test Account Shipping Charges - _TC": [100, 0],
			"_Test Account Excise Duty - _TC": [140, 0],
			"_Test Account Education Cess - _TC": [2.8, 0],
			"_Test Account S&H Education Cess - _TC": [1.4, 0],
			"_Test Account CST - _TC": [29.88, 0],
			"_Test Account VAT - _TC": [156.25, 0],
			"_Test Account Discount - _TC": [0, 168.03],
		}
		gl_entries = webnotes.conn.sql("""select account, debit, credit from `tabGL Entry`
			where voucher_type = 'Purchase Invoice' and voucher_no = %s""", dl[0].name, as_dict=1)
		for d in gl_entries:
			self.assertEqual([d.debit, d.credit], expected_gl_entries.get(d.account))
Esempio n. 18
0
def get_rates_as_per_price_list(args, item_doclist=None):
    if not item_doclist:
        item_doclist = webnotes.model_wrapper("Item", args.item_code).doclist

    result = item_doclist.get({
        "parentfield": "ref_rate_details",
        "price_list_name": args.price_list_name,
        "ref_currency": args.price_list_currency,
        "buying": 1
    })

    if result:
        purchase_ref_rate = flt(result[0].ref_rate) * flt(
            args.plc_conversion_rate)
        conversion_rate = flt(args.conversion_rate) or 1.0
        return webnotes._dict({
            "purchase_ref_rate":
            purchase_ref_rate,
            "purchase_rate":
            purchase_ref_rate,
            "rate":
            purchase_ref_rate,
            "discount_rate":
            0,
            "import_ref_rate":
            purchase_ref_rate / conversion_rate,
            "import_rate":
            purchase_ref_rate / conversion_rate
        })
    else:
        return webnotes._dict()
Esempio n. 19
0
	def set_status(doctype, name):
		w = webnotes.model_wrapper(doctype, name)
		w.ignore_permissions = True
		w.doc.status = is_system_user and "Replied" or status
		w.doc.save()
		if mail:
			mail.save_attachments_in_doc(w.doc)
Esempio n. 20
0
def add_sales_communication(subject, content, sender, real_name, mail=None, 
	status="Open", date=None):
	def set_status(doctype, name):
		w = webnotes.model_wrapper(doctype, name)
		w.ignore_permissions = True
		w.doc.status = is_system_user and "Replied" or status
		w.doc.save()
		if mail:
			mail.save_attachments_in_doc(w.doc)

	lead_name = webnotes.conn.get_value("Lead", {"email_id": sender})
	contact_name = webnotes.conn.get_value("Contact", {"email_id": sender})
	is_system_user = webnotes.conn.get_value("Profile", sender)

	if not (lead_name or contact_name):
		# none, create a new Lead
		lead = webnotes.model_wrapper({
			"doctype":"Lead",
			"lead_name": real_name or sender,
			"email_id": sender,
			"status": status,
			"source": "Email"
		})
		lead.ignore_permissions = True
		lead.insert()
		lead_name = lead.doc.name

	make(content=content, sender=sender, subject=subject,
		lead=lead_name, contact=contact_name, date=date)
	
	if contact_name:
		set_status("Contact", contact_name)
	elif lead_name:
		set_status("Lead", lead_name)
Esempio n. 21
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

    name = webnotes.conn.get_value("Lead", {"email_id": sender}, "name")
    if name:
        lead = webnotes.model_wrapper("Lead", name)
        lead.doc.status = status
        lead.ignore_permissions = True
        lead.save()
    else:
        lead = webnotes.model_wrapper({
            "doctype": "Lead",
            "lead_name": sender,
            "email_id": sender,
            "status": status,
            "source": "Website"
        })
        lead.ignore_permissions = True
        lead.insert()

    make(content=message,
         sender=sender,
         subject=subject,
         doctype="Lead",
         name=lead.doc.name,
         lead=lead.doc.name)

    # guest method, cap max writes per hour
    if webnotes.conn.sql("""select count(*) from `tabCommunication`
		where TIMEDIFF(NOW(), modified) < '01:00:00'"""
                         )[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'
Esempio n. 22
0
	def add_ac(self,arg):
		ac = webnotes.model_wrapper(eval(arg))
		ac.doc.doctype = "Account"
		ac.doc.old_parent = ""
		ac.doc.freeze_account = "No"
		ac.insert()

		return ac.doc.name
Esempio n. 23
0
def add_role(profile, role):
	profile_wrapper = webnotes.model_wrapper("Profile", profile)
	profile_wrapper.doclist.append({
		"doctype": "UserRole",
		"parentfield": "user_roles",
		"role": role
	})
	profile_wrapper.save()
Esempio n. 24
0
    def add_cc(self, arg):
        cc = webnotes.model_wrapper(eval(arg))
        cc.doc.doctype = "Cost Center"
        cc.doc.old_parent = ""
        cc.ignore_permissions = 1
        cc.insert()

        return cc.doc.name
Esempio n. 25
0
	def onload(self):
		"""load address"""
		if self.doc.query_options:
			self.doc.query_options = filter(None, self.doc.query_options.replace(",", "\n").split())
		else:
			self.doc.query_options = ["Sales", "Support", "General"]
		if self.doc.address:
			self.address = webnotes.model_wrapper("Address", self.doc.address).doc
Esempio n. 26
0
def submit(doclist):
	if isinstance(doclist, basestring):
		doclist = json.loads(doclist)

	doclistobj = webnotes.model_wrapper(doclist)
	doclistobj.submit()
	
	return [d.fields for d in doclist]
Esempio n. 27
0
    def add_ac(self, arg):
        ac = webnotes.model_wrapper(eval(arg))
        ac.doc.doctype = "Account"
        ac.doc.old_parent = ""
        ac.doc.freeze_account = "No"
        ac.ignore_permissions = 1
        ac.insert()

        return ac.doc.name
Esempio n. 28
0
 def make_entry(self, args):
     args.update({"doctype": "Stock Ledger Entry"})
     if args.get("warehouse"):
         args["warehouse_type"] = webnotes.conn.get_value(
             'Warehouse', args["warehouse"], 'warehouse_type')
     sle = webnotes.model_wrapper([args])
     sle.ignore_permissions = 1
     sle.insert()
     return sle.doc.name
Esempio n. 29
0
	def make_entry(self, args):
		args.update({"doctype": "Stock Ledger Entry"})
		if args.get("warehouse"):
			args["warehouse_type"] = webnotes.conn.get_value('Warehouse' , args["warehouse"],
				'warehouse_type')
		sle = webnotes.model_wrapper([args])
		sle.ignore_permissions = 1
		sle.insert()
		return sle.doc.name
Esempio n. 30
0
	def insert_purchase_request(self, items_to_be_requested, fiscal_year):
		purchase_request_list = []
		if items_to_be_requested:
			for item in items_to_be_requested:
				item_wrapper = webnotes.model_wrapper("Item", item)
				pr_doclist = [
					{
						"doctype": "Purchase Request",
						"__islocal": 1,
						"naming_series": "IDT",
						"transaction_date": nowdate(),
						"status": "Draft",
						"company": self.doc.company,
						"fiscal_year": fiscal_year,
						"requested_by": webnotes.session.user,
						"remark": "Automatically raised from Production Planning Tool"
					},
					{
						"doctype": "Purchase Request Item",
						"__islocal": 1,
						"parentfield": "indent_details",
						"item_code": item,
						"item_name": item_wrapper.doc.item_name,
						"description": item_wrapper.doc.description,
						"uom": item_wrapper.doc.stock_uom,
						"item_group": item_wrapper.doc.item_group,
						"brand": item_wrapper.doc.brand,
						"qty": items_to_be_requested[item],
						"schedule_date": add_days(nowdate(), cint(item_wrapper.doc.lead_time_days)),
						"warehouse": self.doc.purchase_request_for_warehouse
					}
				]
				pr_wrapper = webnotes.model_wrapper(pr_doclist)
				pr_wrapper.ignore_permissions = 1
				pr_wrapper.submit()
				purchase_request_list.append(pr_wrapper.doc.name)
			
			if purchase_request_list:
				pur_req = ["""<a href="#Form/Purchase Request/%s" target="_blank">%s</a>""" % \
					(p, p) for p in purchase_request_list]
				webnotes.msgprint("Following Purchase Request created successfully: \n%s" % 
					"\n".join(pur_req))
		else:
			webnotes.msgprint("Nothing to request")
Esempio n. 31
0
	def test_serialized_stock_entry(self):
		data = [["2012-01-01", "01:00", "10001", 400, 400],
			["2012-01-01", "03:00", "10002", 500, 700],
			["2012-01-01", "04:00", "10003", 700, 700],
			["2012-01-01", "05:00", "10004", 1200, 800],
			["2012-01-01", "05:00", "10005", 800, 800],
			["2012-01-01", "02:00", "10006", 1200, 800],
			["2012-01-01", "06:00", "10007", 1500, 900]]
		for d in data:
			webnotes.model_wrapper([{
				"doctype": "Serial No",
				"item_code": "Nebula 8",
				"warehouse": "Default Warehouse", 
				"status": "In Store",
				"sle_exists": 0,
				"purchase_date": d[0],
				"purchase_time": d[1],
				"serial_no": d[2],
				"purchase_rate": d[3],
				"company": company,
			}]).insert()
			
		for d in data:
			res = webnotes.conn.sql("""select valuation_rate from `tabStock Ledger Entry`
				where posting_date=%s and posting_time=%s and actual_qty=1 and serial_no=%s""",
				(d[0], d[1], d[2]))
			self.assertEquals(res[0][0], d[4])
		
		print "deleted"
		webnotes.delete_doc("Serial No", "10002")
		
		test_data = [["10001", 400, 400],
			["10003", 700, 766.666667],
			["10004", 1200, 875],
			["10005", 800, 860],
			["10006", 1200, 800],
			["10007", 1500, 966.666667]]
		
		for d in test_data:
			res = webnotes.conn.sql("""select valuation_rate from `tabStock Ledger Entry`
				where actual_qty=1 and serial_no=%s""", (d[0],))
			self.assertEquals(res[0][0], d[2])
Esempio n. 32
0
def cancel(doctype=None, name=None):
	"""cancel a doclist"""
	try:
		wrapper = webnotes.model_wrapper(doctype, name)
		wrapper.cancel()
		send_updated_docs(wrapper)
		
	except Exception, e:
		webnotes.errprint(webnotes.utils.getTraceback())
		webnotes.msgprint(webnotes._("Did not cancel"))
		raise e
Esempio n. 33
0
def add_cc(args=None):
	if not args:
		args = webnotes.form_dict
		args.pop("cmd")
		
	cc = webnotes.model_wrapper(args)
	cc.doc.doctype = "Cost Center"
	cc.doc.old_parent = ""
	cc.ignore_permissions = 1
	cc.insert()
	return cc.doc.name
Esempio n. 34
0
	def create_custom_field_for_workflow_state(self):
		doctypeobj = webnotes.get_doctype(self.doc.document_type)
		if not doctypeobj.get({"doctype":"DocField", 
			"fieldname":self.doc.workflow_state_field}):
			
			# create custom field
			webnotes.model_wrapper([{
				"doctype":"Custom Field",
				"dt": self.doc.document_type,
				"__islocal": 1,
				"fieldname": self.doc.workflow_state_field,
				"label": self.doc.workflow_state_field.replace("_", " ").title(),
				"hidden": 1,
				"fieldtype": "Link",
				"options": "Workflow State",
				"insert_after": doctypeobj.get({"doctype":"DocField"})[-1].label
			}]).save()
			
			webnotes.msgprint("Created Custom Field '%s' in '%s'" % (self.doc.workflow_state_field,
				self.doc.document_type))
Esempio n. 35
0
 def onload(self):
     """load address"""
     if self.doc.query_options:
         self.doc.query_options = filter(
             None,
             self.doc.query_options.replace(",", "\n").split())
     else:
         self.doc.query_options = ["Sales", "Support", "General"]
     if self.doc.address:
         self.address = webnotes.model_wrapper("Address",
                                               self.doc.address).doc
Esempio n. 36
0
    def test_serialized_stock_entry(self):
        data = [["2012-01-01", "01:00", "10001", 400, 400],
                ["2012-01-01", "03:00", "10002", 500, 700],
                ["2012-01-01", "04:00", "10003", 700, 700],
                ["2012-01-01", "05:00", "10004", 1200, 800],
                ["2012-01-01", "05:00", "10005", 800, 800],
                ["2012-01-01", "02:00", "10006", 1200, 800],
                ["2012-01-01", "06:00", "10007", 1500, 900]]
        for d in data:
            webnotes.model_wrapper([{
                "doctype": "Serial No",
                "item_code": "Nebula 8",
                "warehouse": "Default Warehouse",
                "status": "In Store",
                "sle_exists": 0,
                "purchase_date": d[0],
                "purchase_time": d[1],
                "serial_no": d[2],
                "purchase_rate": d[3],
                "company": company,
            }]).insert()

        for d in data:
            res = webnotes.conn.sql(
                """select valuation_rate from `tabStock Ledger Entry`
				where posting_date=%s and posting_time=%s and actual_qty=1 and serial_no=%s""",
                (d[0], d[1], d[2]))
            self.assertEquals(res[0][0], d[4])

        print "deleted"
        webnotes.delete_doc("Serial No", "10002")

        test_data = [["10001", 400, 400], ["10003", 700, 766.666667],
                     ["10004", 1200, 875], ["10005", 800, 860],
                     ["10006", 1200, 800], ["10007", 1500, 966.666667]]

        for d in test_data:
            res = webnotes.conn.sql(
                """select valuation_rate from `tabStock Ledger Entry`
				where actual_qty=1 and serial_no=%s""", (d[0], ))
            self.assertEquals(res[0][0], d[2])
	def submit_stock_reconciliation(self, qty, rate, posting_date, posting_time):
		return webnotes.model_wrapper([{
			"doctype": "Stock Reconciliation",
			"name": "RECO-001",
			"__islocal": 1,
			"posting_date": posting_date,
			"posting_time": posting_time,
			"reconciliation_json": json.dumps([
				["Item Code", "Warehouse", "Quantity", "Valuation Rate"],
				["Android Jack D", "Default Warehouse", qty, rate]
			]),
		}]).submit()
Esempio n. 38
0
def save(doclist):
	"""insert or update from form query"""
	if isinstance(doclist, basestring):
		doclist = json.loads(doclist)
		
	if not webnotes.has_permission(doclist[0]["doctype"], "write"):
		webnotes.msgprint("No Write Permission", raise_exception=True)

	doclistobj = webnotes.model_wrapper(doclist)
	doclistobj.save()
	
	return [d.fields for d in doclist]
Esempio n. 39
0
def add_ac(args=None):
	if not args:
		args = webnotes.form_dict
		args.pop("cmd")
	
	ac = webnotes.model_wrapper(args)
	ac.doc.doctype = "Account"
	ac.doc.old_parent = ""
	ac.doc.freeze_account = "No"
	ac.ignore_permissions = 1
	ac.insert()
	return ac.doc.name
Esempio n. 40
0
def move_remarks_to_comments():
    from webnotes.utils import get_fullname
    result = webnotes.conn.sql(
        """select name, remark, modified_by from `tabStock Reconciliation`
		where ifnull(remark, '')!=''""")
    fullname_map = {}
    for reco, remark, modified_by in result:
        webnotes.model_wrapper([{
            "doctype":
            "Comment",
            "comment":
            remark,
            "comment_by":
            modified_by,
            "comment_by_fullname":
            fullname_map.setdefault(modified_by, get_fullname(modified_by)),
            "comment_doctype":
            "Stock Reconciliation",
            "comment_docname":
            reco
        }]).insert()
Esempio n. 41
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
		
	name = webnotes.conn.get_value("Lead", {"email_id": sender}, "name")
	if name:
		lead = webnotes.model_wrapper("Lead", name)
		lead.doc.status = status
		lead.ignore_permissions = True
		lead.save()
	else:
		lead = webnotes.model_wrapper({
			"doctype":"Lead",
			"lead_name": sender,
			"email_id": sender,
			"status": status,
			"source": "Website"
		})
		lead.ignore_permissions = True
		lead.insert()
	
	make(content=message, sender=sender, subject=subject,
		doctype="Lead", name=lead.doc.name, lead=lead.doc.name)

	
	# guest method, cap max writes per hour
	if webnotes.conn.sql("""select count(*) from `tabCommunication`
		where TIMEDIFF(NOW(), modified) < '01:00:00'""")[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'
Esempio n. 42
0
def insert(doclist):
    if not isinstance(doclist, list):
        doclist = [doclist]

    for d in doclist:
        if isinstance(d, dict):
            d["__islocal"] = 1
        else:
            d.fields["__islocal"] = 1

    wrapper = webnotes.model_wrapper(doclist)
    wrapper.save()

    return wrapper
Esempio n. 43
0
    def create_property_setter(self):
        idx_label_list, field_list = get_fields_label(self.doc.dt, 0)
        label_index = idx_label_list.index(self.doc.insert_after)
        if label_index == -1: return

        prev_field = field_list[label_index]
        webnotes.conn.sql(
            """\
			DELETE FROM `tabProperty Setter`
			WHERE doc_type = %s
			AND field_name = %s
			AND property = 'previous_field'""", (self.doc.dt, self.doc.fieldname))

        webnotes.model_wrapper([{
            'doctype': "Property Setter",
            'doctype_or_field': 'DocField',
            'doc_type': self.doc.dt,
            'field_name': self.doc.fieldname,
            'property': 'previous_field',
            'value': prev_field,
            'property_type': 'Data',
            'select_doctype': self.doc.dt,
            '__islocal': 1
        }]).save()
Esempio n. 44
0
	def get_bin(self, item_code, warehouse=None):
		warehouse = warehouse or self.doc.name
		bin = sql("select name from tabBin where item_code = %s and \
				warehouse = %s", (item_code, warehouse))
		bin = bin and bin[0][0] or ''
		if not bin:
			bin_wrapper = webnotes.model_wrapper([{
				"doctype": "Bin",
				"item_code": item_code,
				"warehouse": warehouse,
			}])
			bin_wrapper.ignore_permissions = 1
			bin_wrapper.insert()
			
			bin_obj = bin_wrapper.make_obj()
		else:
			bin_obj = get_obj('Bin', bin)
		return bin_obj
Esempio n. 45
0
def prepare_args(page_name):
    if page_name == 'index':
        page_name = get_home_page()

    if page_name in get_template_pages():
        args = webnotes._dict({
            'template': 'pages/%s.html' % page_name,
            'name': page_name,
        })
        if page_name in page_settings_map:
            args.obj = webnotes.model_wrapper(page_settings_map[page_name]).obj
    else:
        args = get_doc_fields(page_name)

    if not args:
        return False

    args.update(get_outer_env())

    return args
Esempio n. 46
0
def execute():
    import webnotes
    for dt in webnotes.conn.sql("""select name, issingle from tabDocType"""):
        if dt[1]:
            webnotes.conn.sql(
                """update tabDocPerm set report = 0 where parent = %s""",
                dt[0])

        doctype = webnotes.model_wrapper("DocType", dt[0])
        for pl in [1, 2, 3]:
            if not doctype.doclist.get({
                    "doctype": "DocField",
                    "permlevel": pl
            }):
                if doctype.doclist.get({
                        "doctype": "DocPerm",
                        "permlevel": pl
                }):
                    webnotes.conn.sql(
                        """delete from `tabDocPerm` 
						where parent = %s and permlevel = %s""", (dt[0], pl))
Esempio n. 47
0
    def insert_entries(self, opts, row):
        """Insert Stock Ledger Entries"""
        args = {
            "doctype": "Stock Ledger Entry",
            "item_code": row.item_code,
            "warehouse": row.warehouse,
            "posting_date": self.doc.posting_date,
            "posting_time": self.doc.posting_time,
            "voucher_type": self.doc.doctype,
            "voucher_no": self.doc.name,
            "company": webnotes.conn.get_default("company"),
            "is_cancelled": "No",
        }
        args.update(opts)
        # create stock ledger entry
        sle_wrapper = webnotes.model_wrapper([args])
        sle_wrapper.ignore_permissions = 1
        sle_wrapper.insert()

        # update bin
        webnotes.get_obj('Warehouse', row.warehouse).update_bin(args)

        return sle_wrapper
Esempio n. 48
0
    def insert_purchase_request(self, items_to_be_requested, fiscal_year):
        purchase_request_list = []
        if items_to_be_requested:
            for item in items_to_be_requested:
                item_wrapper = webnotes.model_wrapper("Item", item)
                pr_doclist = [{
                    "doctype":
                    "Purchase Request",
                    "__islocal":
                    1,
                    "naming_series":
                    "IDT",
                    "transaction_date":
                    nowdate(),
                    "status":
                    "Draft",
                    "company":
                    self.doc.company,
                    "fiscal_year":
                    fiscal_year,
                    "requested_by":
                    webnotes.session.user,
                    "remark":
                    "Automatically raised from Production Planning Tool"
                }, {
                    "doctype":
                    "Purchase Request Item",
                    "__islocal":
                    1,
                    "parentfield":
                    "indent_details",
                    "item_code":
                    item,
                    "item_name":
                    item_wrapper.doc.item_name,
                    "description":
                    item_wrapper.doc.description,
                    "uom":
                    item_wrapper.doc.stock_uom,
                    "item_group":
                    item_wrapper.doc.item_group,
                    "brand":
                    item_wrapper.doc.brand,
                    "qty":
                    items_to_be_requested[item],
                    "schedule_date":
                    add_days(nowdate(), cint(item_wrapper.doc.lead_time_days)),
                    "warehouse":
                    self.doc.purchase_request_for_warehouse
                }]
                pr_wrapper = webnotes.model_wrapper(pr_doclist)
                pr_wrapper.ignore_permissions = 1
                pr_wrapper.submit()
                purchase_request_list.append(pr_wrapper.doc.name)

            if purchase_request_list:
                pur_req = ["""<a href="#Form/Purchase Request/%s" target="_blank">%s</a>""" % \
                 (p, p) for p in purchase_request_list]
                webnotes.msgprint(
                    "Following Purchase Request created successfully: \n%s" %
                    "\n".join(pur_req))
        else:
            webnotes.msgprint("Nothing to request")
Esempio n. 49
0
def get_item_details(args):
    """
		args = {
			"doctype": "",
			"docname": "",
			"item_code": "",
			"warehouse": None,
			"supplier": None,
			"transaction_date": None,
			"conversion_rate": 1.0
		}
	"""
    if isinstance(args, basestring):
        args = json.loads(args)

    args = webnotes._dict(args)

    item_wrapper = webnotes.model_wrapper("Item", args.item_code)
    item = item_wrapper.doc

    from stock.utils import validate_end_of_life
    validate_end_of_life(item.name, item.end_of_life)

    # fetch basic values
    out = webnotes._dict()
    out.update({
        "item_name":
        item.item_name,
        "item_group":
        item.item_group,
        "brand":
        item.brand,
        "description":
        item.description,
        "qty":
        0,
        "stock_uom":
        item.stock_uom,
        "uom":
        item.stock_uom,
        "conversion_factor":
        1,
        "warehouse":
        args.warehouse or item.default_warehouse,
        "item_tax_rate":
        json.dumps(
            dict(
                ([d.tax_type, d.tax_rate]
                 for d in item_wrapper.doclist.get({"parentfield": "item_tax"})
                 ))),
        "batch_no":
        None,
        "expense_head":
        item.purchase_account,
        "cost_center":
        item.cost_center
    })

    if args.supplier:
        item_supplier = item_wrapper.doclist.get({
            "parentfield": "item_supplier_details",
            "supplier": args.supplier
        })
        if item_supplier:
            out["supplier_part_no"] = item_supplier[0].supplier_part_no

    if out.warehouse:
        out.projected_qty = webnotes.conn.get_value("Bin", {
            "item_code": item.name,
            "warehouse": out.warehouse
        }, "projected_qty")

    if args.transaction_date and item.lead_time_days:
        out.schedule_date = out.lead_time_date = add_days(
            args.transaction_date, item.lead_time_days)

    # set zero
    out.purchase_ref_rate = out.discount_rate = out.purchase_rate = \
     out.import_ref_rate = out.import_rate = 0.0

    if args.doctype in [
            "Purchase Order", "Purchase Invoice", "Purchase Receipt",
            "Supplier Quotation"
    ]:
        # try fetching from price list
        if args.price_list_name and args.price_list_currency:
            rates_as_per_price_list = get_rates_as_per_price_list(
                args, item_wrapper.doclist)
            if rates_as_per_price_list:
                out.update(rates_as_per_price_list)

        # if not found, fetch from last purchase transaction
        if not out.purchase_rate:
            last_purchase = get_last_purchase_details(item.name, args.docname,
                                                      args.conversion_rate)
            if last_purchase:
                out.update(last_purchase)

    return out
Esempio n. 50
0
def set_status(name, status):
    st = webnotes.model_wrapper("Support Ticket", name)
    st.doc.status = status
    st.save()