Пример #1
0
	def validate(self):
		self.validate_mandatory()
		self.validate_item()
		self.actual_amt_check()
		self.check_stock_frozen_date()
		self.scrub_posting_time()
		self.doc.fiscal_year = get_fiscal_year(self.doc.posting_date)[0]
Пример #2
0
def make_new_invoice(ref_wrapper, posting_date):
    from webnotes.model.wrapper import clone
    from accounts.utils import get_fiscal_year
    new_invoice = clone(ref_wrapper)

    mcount = month_map[ref_wrapper.doc.recurring_type]

    new_invoice.doc.fields.update({
     "posting_date": posting_date,
     "aging_date": posting_date,

     "due_date": add_days(posting_date, cint(date_diff(ref_wrapper.doc.due_date,
      ref_wrapper.doc.posting_date))),

     "invoice_period_from_date": \
      get_next_date(ref_wrapper.doc.invoice_period_from_date, mcount),

     "invoice_period_to_date": \
      get_next_date(ref_wrapper.doc.invoice_period_to_date, mcount),
     "fiscal_year": get_fiscal_year(posting_date)[0],
     "owner": ref_wrapper.doc.owner,
    })

    new_invoice.submit()

    return new_invoice
Пример #3
0
 def validate(self):
     self.validate_mandatory()
     self.validate_item()
     self.actual_amt_check()
     self.check_stock_frozen_date()
     self.scrub_posting_time()
     self.doc.fiscal_year = get_fiscal_year(self.doc.posting_date)[0]
Пример #4
0
def make_new_invoice(ref_wrapper, posting_date):
	from webnotes.model.bean import clone
	from accounts.utils import get_fiscal_year
	new_invoice = clone(ref_wrapper)
	
	mcount = month_map[ref_wrapper.doc.recurring_type]
	
	invoice_period_from_date = get_next_date(ref_wrapper.doc.invoice_period_from_date, mcount)
	
	# get last day of the month to maintain period if the from date is first day of its own month 
	# and to date is the last day of its own month
	if (cstr(get_first_day(ref_wrapper.doc.invoice_period_from_date)) == \
			cstr(ref_wrapper.doc.invoice_period_from_date)) and \
		(cstr(get_last_day(ref_wrapper.doc.invoice_period_to_date)) == \
			cstr(ref_wrapper.doc.invoice_period_to_date)):
		invoice_period_to_date = get_last_day(get_next_date(ref_wrapper.doc.invoice_period_to_date,
			mcount))
	else:
		invoice_period_to_date = get_next_date(ref_wrapper.doc.invoice_period_to_date, mcount)
	
	new_invoice.doc.fields.update({
		"posting_date": posting_date,
		"aging_date": posting_date,
		"due_date": add_days(posting_date, cint(date_diff(ref_wrapper.doc.due_date,
			ref_wrapper.doc.posting_date))),
		"invoice_period_from_date": invoice_period_from_date,
		"invoice_period_to_date": invoice_period_to_date,
		"fiscal_year": get_fiscal_year(posting_date)[0],
		"owner": ref_wrapper.doc.owner,
	})
	
	new_invoice.submit()
	
	return new_invoice
Пример #5
0
    def raise_purchase_request(self):
        """
			Raise Material Request if projected qty is less than qty required
			Requested qty should be shortage qty considering minimum order qty
		"""
        self.validate_data()
        if not self.doc.purchase_request_for_warehouse:
            webnotes.msgprint("Please enter Warehouse for which Material Request will be raised", raise_exception=1)

        bom_dict = self.get_distinct_items_and_boms()[0]
        self.get_raw_materials(bom_dict)

        if not self.item_dict:
            return

        item_projected_qty = self.get_projected_qty()

        from accounts.utils import get_fiscal_year

        fiscal_year = get_fiscal_year(nowdate())[0]

        items_to_be_requested = webnotes._dict()
        for item in self.item_dict:
            if flt(self.item_dict[item][0]) > item_projected_qty.get(item, 0):
                # shortage
                requested_qty = flt(self.item_dict[item][0]) - item_projected_qty.get(item, 0)
                # comsider minimum order qty
                requested_qty = (
                    requested_qty > flt(self.item_dict[item][3]) and requested_qty or flt(self.item_dict[item][3])
                )
                items_to_be_requested[item] = requested_qty

        self.insert_purchase_request(items_to_be_requested, fiscal_year)
Пример #6
0
def make_new_invoice(ref_wrapper, posting_date):
	from webnotes.model.wrapper import clone
	from accounts.utils import get_fiscal_year
	new_invoice = clone(ref_wrapper)
	
	mcount = month_map[ref_wrapper.doc.recurring_type]
		
	new_invoice.doc.fields.update({
		"posting_date": posting_date,
		"aging_date": posting_date,
		
		"due_date": add_days(posting_date, cint(date_diff(ref_wrapper.doc.due_date,
			ref_wrapper.doc.posting_date))),
			
		"invoice_period_from_date": \
			get_next_date(ref_wrapper.doc.invoice_period_from_date, mcount),
			
		"invoice_period_to_date": \
			get_next_date(ref_wrapper.doc.invoice_period_to_date, mcount),
		"fiscal_year": get_fiscal_year(posting_date)[0],
		"owner": ref_wrapper.doc.owner,
	})
	
	new_invoice.submit()
	
	return new_invoice
Пример #7
0
    def raise_purchase_request(self):
        """
			Raise Material Request if projected qty is less than qty required
			Requested qty should be shortage qty considering minimum order qty
		"""
        if not self.doc.purchase_request_for_warehouse:
            webnotes.msgprint(
                "Please enter Warehouse for which Material Request will be raised",
                raise_exception=1)

        bom_dict = self.get_distinct_items_and_boms()[0]
        self.get_raw_materials(bom_dict)
        item_projected_qty = self.get_projected_qty()

        from accounts.utils import get_fiscal_year
        fiscal_year = get_fiscal_year(nowdate())[0]

        items_to_be_requested = webnotes._dict()
        for item in self.item_dict:
            if flt(self.item_dict[item][0]) > item_projected_qty[item]:
                # shortage
                requested_qty = flt(
                    self.item_dict[item][0]) - item_projected_qty[item]
                # comsider minimum order qty
                requested_qty = requested_qty > flt(self.item_dict[item][3]) and \
                 requested_qty or flt(self.item_dict[item][3])
                items_to_be_requested[item] = requested_qty

        self.insert_purchase_request(items_to_be_requested, fiscal_year)
Пример #8
0
def make_new_invoice(ref_wrapper, posting_date):
	from webnotes.model.bean import clone
	from accounts.utils import get_fiscal_year
	new_invoice = clone(ref_wrapper)
	
	mcount = month_map[ref_wrapper.doc.recurring_type]
	
	invoice_period_from_date = get_next_date(ref_wrapper.doc.invoice_period_from_date, mcount)
	
	# get last day of the month to maintain period if the from date is first day of its own month 
	# and to date is the last day of its own month
	if (cstr(get_first_day(ref_wrapper.doc.invoice_period_from_date)) == \
			cstr(ref_wrapper.doc.invoice_period_from_date)) and \
		(cstr(get_last_day(ref_wrapper.doc.invoice_period_to_date)) == \
			cstr(ref_wrapper.doc.invoice_period_to_date)):
		invoice_period_to_date = get_last_day(get_next_date(ref_wrapper.doc.invoice_period_to_date,
			mcount))
	else:
		invoice_period_to_date = get_next_date(ref_wrapper.doc.invoice_period_to_date, mcount)
	
	new_invoice.doc.fields.update({
		"posting_date": posting_date,
		"aging_date": posting_date,
		"due_date": add_days(posting_date, cint(date_diff(ref_wrapper.doc.due_date,
			ref_wrapper.doc.posting_date))),
		"invoice_period_from_date": invoice_period_from_date,
		"invoice_period_to_date": invoice_period_to_date,
		"fiscal_year": get_fiscal_year(posting_date)[0],
		"owner": ref_wrapper.doc.owner,
	})
	
	new_invoice.submit()
	
	return new_invoice
Пример #9
0
def add_data(w, args):
    from accounts.utils import get_fiscal_year

    dates = get_dates(args)
    employees = get_active_employees()
    existing_attendance_records = get_existing_attendance_records(args)
    for date in dates:
        for employee in employees:
            existing_attendance = {}
            if existing_attendance_records \
             and tuple([date, employee.name]) in existing_attendance_records:
                existing_attendance = existing_attendance_records[tuple(
                    [date, employee.name])]
            row = [
                existing_attendance and existing_attendance.name or "",
                employee.name,
                employee.employee_name,
                date,
                existing_attendance and existing_attendance.status or "",
                get_fiscal_year(date)[0],
                employee.company,
                existing_attendance and existing_attendance.naming_series
                or get_naming_series(),
            ]
            w.writerow(row)
    return w
Пример #10
0
 def submit_stock_reconciliation(self, qty, rate, posting_date,
                                 posting_time):
     stock_reco = webnotes.bean([{
         "doctype":
         "Stock Reconciliation",
         "posting_date":
         posting_date,
         "posting_time":
         posting_time,
         "fiscal_year":
         get_fiscal_year(posting_date)[0],
         "company":
         "_Test Company",
         "expense_account":
         "Stock Adjustment - _TC",
         "cost_center":
         "_Test Cost Center - _TC",
         "reconciliation_json":
         json.dumps(
             [["Item Code", "Warehouse", "Quantity", "Valuation Rate"],
              ["_Test Item", "_Test Warehouse - _TC", qty, rate]]),
     }])
     stock_reco.insert()
     stock_reco.submit()
     return stock_reco
Пример #11
0
 def set_missing_values(self, for_validate=False):
     for fieldname in ["posting_date", "transaction_date"]:
         if not self.doc.fields.get(fieldname) and self.meta.get_field(
                 fieldname):
             self.doc.fields[fieldname] = today()
             if not self.doc.fiscal_year:
                 self.doc.fiscal_year = get_fiscal_year(
                     self.doc.fields[fieldname])[0]
Пример #12
0
def execute():
	item_map = {}
	for item in webnotes.conn.sql("""select * from tabItem""", as_dict=1):
		item_map.setdefault(item.name, item)
	
	warehouse_map = get_warehosue_map()
	naming_series = "STE/13/"
	
	for company in webnotes.conn.sql("select name from tabCompany"):
		stock_entry = [{
			"doctype": "Stock Entry",
			"naming_series": naming_series,
			"posting_date": nowdate(),
			"posting_time": nowtime(),
			"purpose": "Material Transfer",
			"company": company[0],
			"remarks": "Material Transfer to activate perpetual inventory",
			"fiscal_year": get_fiscal_year(nowdate())[0]
		}]
		expense_account = "Cost of Goods Sold - NISL"
		cost_center = "Default CC Ledger - NISL"
		
		for bin in webnotes.conn.sql("""select * from tabBin bin where ifnull(item_code, '')!='' 
				and ifnull(warehouse, '') in (%s) and ifnull(actual_qty, 0) != 0
				and (select company from tabWarehouse where name=bin.warehouse)=%s""" %
				(', '.join(['%s']*len(warehouse_map)), '%s'), 
				(warehouse_map.keys() + [company[0]]), as_dict=1):
			item_details = item_map[bin.item_code]
			new_warehouse = warehouse_map[bin.warehouse].get("fixed_asset_warehouse") \
				if cstr(item_details.is_asset_item) == "Yes" \
				else warehouse_map[bin.warehouse].get("current_asset_warehouse")
				
			if item_details.has_serial_no == "Yes":
				serial_no = "\n".join([d[0] for d in webnotes.conn.sql("""select name 
					from `tabSerial No` where item_code = %s and warehouse = %s 
					and status in ('Available', 'Sales Returned')""", 
					(bin.item_code, bin.warehouse))])
			else:
				serial_no = None
			
			stock_entry.append({
				"doctype": "Stock Entry Detail",
				"parentfield": "mtn_details",
				"s_warehouse": bin.warehouse,
				"t_warehouse": new_warehouse,
				"item_code": bin.item_code,
				"description": item_details.description,
				"qty": bin.actual_qty,
				"transfer_qty": bin.actual_qty,
				"uom": item_details.stock_uom,
				"stock_uom": item_details.stock_uom,
				"conversion_factor": 1,
				"expense_account": expense_account,
				"cost_center": cost_center,
				"serial_no": serial_no
			})
		
		webnotes.bean(stock_entry).insert()
Пример #13
0
	def validate_fiscal_year(self, fiscal_year, transaction_date, label):
		from accounts.utils import get_fiscal_year
		if get_fiscal_year(transaction_date)[0] != fiscal_year:
			msgprint(("%(label)s '%(posting_date)s': " + _("not within Fiscal Year") + \
				": '%(fiscal_year)s'") % {
					"label": label,
					"posting_date": formatdate(transaction_date),
					"fiscal_year": fiscal_year
				}, raise_exception=1)
def get_achieved_details(filters):
	start_date, end_date = get_fiscal_year(fiscal_year = filters["fiscal_year"])[1:]

	return webnotes.conn.sql("""select soi.item_code, soi.qty, soi.amount, so.transaction_date, 
		so.territory, MONTHNAME(so.transaction_date) as month_name 
		from `tabSales Order Item` soi, `tabSales Order` so 
		where soi.parent=so.name and so.docstatus=1 and so.transaction_date>=%s and 
		so.transaction_date<=%s""" % ('%s', '%s'), 
		(start_date, end_date), as_dict=1)
Пример #15
0
	def validate_fiscal_year(self, fiscal_year, transaction_date, label):
		from accounts.utils import get_fiscal_year
		if get_fiscal_year(transaction_date)[0] != fiscal_year:
			msgprint(("%(label)s '%(posting_date)s': " + _("not within Fiscal Year") + \
				": '%(fiscal_year)s'") % {
					"label": label,
					"posting_date": formatdate(transaction_date),
					"fiscal_year": fiscal_year
				}, raise_exception=1)
Пример #16
0
	def validate_posting_date(self):
		from accounts.utils import get_fiscal_year
		self.year_start_date = get_fiscal_year(self.doc.posting_date, self.doc.fiscal_year)[1]

		pce = webnotes.conn.sql("""select name from `tabPeriod Closing Voucher`
			where posting_date > %s and fiscal_year = %s and docstatus = 1""", 
			(self.doc.posting_date, self.doc.fiscal_year))
		if pce and pce[0][0]:
			webnotes.throw(_("Another Period Closing Entry") + ": " + cstr(pce[0][0]) + 
				  _("has been made after posting date") + ": " + self.doc.posting_date)
Пример #17
0
	def validate_posting_date(self):
		from accounts.utils import get_fiscal_year
		self.year_start_date = get_fiscal_year(self.doc.posting_date)[1]

		pce = webnotes.conn.sql("""select name from `tabPeriod Closing Voucher`
			where posting_date > %s and fiscal_year = %s and docstatus = 1""", 
			(self.doc.posting_date, self.doc.fiscal_year))
		if pce and pce[0][0]:
			webnotes.throw(_("Another Period Closing Entry") + ": " + cstr(pce[0][0]) + 
				  _("has been made after posting date") + ": " + self.doc.posting_date)
def get_achieved_details(filters):
	start_date, end_date = get_fiscal_year(fiscal_year = filters["fiscal_year"])[1:]
	
	return webnotes.conn.sql("""select soi.item_code, soi.qty, soi.amount, so.transaction_date, 
		st.sales_person, MONTHNAME(so.transaction_date) as month_name 
		from `tabSales Order Item` soi, `tabSales Order` so, `tabSales Team` st 
		where soi.parent=so.name and so.docstatus=1 and 
		st.parent=so.name and so.transaction_date>=%s and 
		so.transaction_date<=%s""" % ('%s', '%s'), 
		(start_date, end_date), as_dict=1)
def execute():
	webnotes.reload_doc("stock", "doctype", "stock_entry")
	webnotes.reload_doc("stock", "doctype", "stock_reconciliation")
	
	for doctype in ["Stock Entry", "Stock Reconciliation"]:
		for name, posting_date in webnotes.conn.sql("""select name, posting_date from `tab%s`
				where ifnull(fiscal_year,'')='' and docstatus=1""" % doctype):
			try:
				fiscal_year = get_fiscal_year(posting_date, 0)[0]
				webnotes.conn.sql("""update `tab%s` set fiscal_year=%s where name=%s""" % \
					(doctype, "%s", "%s"), (fiscal_year, name))
			except FiscalYearError:
				pass
def execute():
	webnotes.reload_doc("stock", "doctype", "stock_entry")
	webnotes.reload_doc("stock", "doctype", "stock_reconciliation")
	
	for doctype in ["Stock Entry", "Stock Reconciliation"]:
		for name, posting_date in webnotes.conn.sql("""select name, posting_date from `tab%s`
				where ifnull(fiscal_year,'')='' and docstatus=1""" % doctype):
			try:
				fiscal_year = get_fiscal_year(posting_date, 0)[0]
				webnotes.conn.sql("""update `tab%s` set fiscal_year=%s where name=%s""" % \
					(doctype, "%s", "%s"), (fiscal_year, name))
			except FiscalYearError:
				pass
Пример #21
0
	def insert_purchase_request(self):
		items_to_be_requested = self.get_requested_items()

		from accounts.utils import get_fiscal_year
		fiscal_year = get_fiscal_year(nowdate())[0]

		purchase_request_list = []
		if items_to_be_requested:
			for item in items_to_be_requested:
				item_wrapper = webnotes.bean("Item", item)
				pr_doclist = [{
					"doctype": "Material Request",
					"__islocal": 1,
					"naming_series": "IDT",
					"transaction_date": nowdate(),
					"status": "Draft",
					"company": self.doc.company,
					"fiscal_year": fiscal_year,
					"requested_by": webnotes.session.user,
					"material_request_type": "Purchase"
				}]
				for sales_order, requested_qty in items_to_be_requested[item].items():
					pr_doclist.append({
						"doctype": "Material 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": requested_qty,
						"schedule_date": add_days(nowdate(), cint(item_wrapper.doc.lead_time_days)),
						"warehouse": self.doc.purchase_request_for_warehouse,
						"sales_order_no": sales_order if sales_order!="No Sales Order" else None
					})

				pr_wrapper = webnotes.bean(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/Material Request/%s" target="_blank">%s</a>""" % \
					(p, p) for p in purchase_request_list]
				msgprint("Material Request(s) created: \n%s" % 
					"\n".join(pur_req))
		else:
			msgprint(_("Nothing to request"))
def get_achieved_details(filters):
	start_date, end_date = get_fiscal_year(fiscal_year = filters["fiscal_year"])[1:]

	item_details = webnotes.conn.sql("""select soi.item_code, soi.qty, soi.amount, so.transaction_date, 
		so.territory, MONTHNAME(so.transaction_date) as month_name 
		from `tabSales Order Item` soi, `tabSales Order` so 
		where soi.parent=so.name and so.docstatus=1 and so.transaction_date>=%s and 
		so.transaction_date<=%s""" % ('%s', '%s'), 
		(start_date, end_date), as_dict=1)

	item_actual_details = {}
	for d in item_details:
		item_actual_details.setdefault(d.territory, {}).setdefault(\
			get_item_group(d.item_code), []).append(d)

	return item_actual_details
def get_achieved_details(filters):
	start_date, end_date = get_fiscal_year(fiscal_year = filters["fiscal_year"])[1:]

	item_details = webnotes.conn.sql("""select soi.item_code, soi.qty, soi.amount, so.transaction_date, 
		so.territory, MONTHNAME(so.transaction_date) as month_name 
		from `tabSales Order Item` soi, `tabSales Order` so 
		where soi.parent=so.name and so.docstatus=1 and so.transaction_date>=%s and 
		so.transaction_date<=%s""" % ('%s', '%s'), 
		(start_date, end_date), as_dict=1)

	item_actual_details = {}
	for d in item_details:
		item_actual_details.setdefault(d.territory, {}).setdefault(\
			get_item_group(d.item_code), []).append(d)

	return item_actual_details
Пример #24
0
	def submit_stock_reconciliation(self, qty, rate, posting_date, posting_time):
		stock_reco = webnotes.bean([{
			"doctype": "Stock Reconciliation",
			"posting_date": posting_date,
			"posting_time": posting_time,
			"fiscal_year": get_fiscal_year(posting_date)[0],
			"company": "_Test Company",
			"expense_account": "Stock Adjustment - _TC",
			"reconciliation_json": json.dumps([
				["Item Code", "Warehouse", "Quantity", "Valuation Rate"],
				["_Test Item", "_Test Warehouse - _TC", qty, rate]
			]),
		}])
		stock_reco.insert()
		stock_reco.submit()
		return stock_reco
Пример #25
0
def add_data(w, args):
	from accounts.utils import get_fiscal_year
	
	dates = get_dates(args)
	employees = get_active_employees()
	existing_attendance_records = get_existing_attendance_records(args)
	for date in dates:
		for employee in employees:
			existing_attendance = {}
			if existing_attendance_records \
				and tuple([date, employee.name]) in existing_attendance_records:
					existing_attendance = existing_attendance_records[tuple([date, employee.name])]
			row = [
				existing_attendance and existing_attendance.name or "",
				employee.name, employee.employee_name, date, 
				existing_attendance and existing_attendance.status or "",
				get_fiscal_year(date)[0], employee.company, 
				existing_attendance and existing_attendance.naming_series or get_naming_series(),
			]
			w.writerow(row)
	return w
Пример #26
0
def create_invoice(auth_key,invoice_type,customer,serial_number,dattime,_type='POST'):
	login =[]
	loginObj = {}
	if len(auth_key[1:-1])<=0 or len(dattime[1:-1])<=0 or len(customer[1:-1])<=0 or len(serial_number[1:-1])<=0 :
		loginObj['status']='401'
		loginObj['error']='Incomplete data to generate Sales Invoice , Please provide token no , Datetime,customer and serial no'
		return loginObj
	qr="select name from `tabauth keys` where auth_key="+auth_key
	res=webnotes.conn.sql(qr)
	rgn=webnotes.conn.sql("select region from `tabFranchise` where contact_email='"+res[0][0]+"'")
	zz=serial_number[1:-1].count(' ')
	xx=serial_number[1:-1].replace('[','').split(' ')
	#xxx=xx.replace(' ','\n')
	yy="select item_code,item_name,description from `tabSerial No` where name='"+cstr(xx[0])+"'"
	zzz=webnotes.conn.sql(yy)
	if not zzz:
          loginObj['status']='402'
          loginObj['error']='Invalid serails no, please try againg'
          return loginObj
	pp="select ref_rate from `tabItem Price` where price_list='Standard Selling' and item_code='"+zzz[0][0]+"'"
	ppp=webnotes.conn.sql(pp)
	if res:
		from webnotes.model.doc import Document
		d = Document('Sales Invoice')
		d.customer=customer[1:-1]
		d.customer_name=customer[1:-1]
		d.region=rgn[0][0]
		d.posting_date=dattime[1:-1]
		d.due_date=dattime[1:-1]
		d.selling_price_list='Standard Selling'
		d.currency='INR'
		d.territory='India'
		if ppp:
			d.net_total_export=ppp[0][0]*zz
			d.grand_total_export=ppp[0][0]*zz
			d.rounded_total_export=ppp[0][0]*zz
			d.outstanding_amount=ppp[0][0]*zz
		d.plc_conversion_rate=1
		from webnotes.utils import nowdate
  		from accounts.utils import get_fiscal_year
   		today = nowdate()
		d.fiscal_year=get_fiscal_year(today)[0]
		d.debit_to=customer[1:-1]+" - P"
		d.is_pos=1
		d.cash_bank_account='Cash - P'
                d.save()
		webnotes.conn.commit()
		e=Document('Sales Invoice Item')
		e.item_code=zzz[0][0]
		e.item_name=zzz[0][1]
		e.description=zzz[0][2]
		e.qty=zz
		e.stock_uom='Nos'
		if ppp:
			e.ref_rate=ppp[0][0]
			e.export_rate=ppp[0][0]
		e.export_amount='0'
		e.income_account='Sales - P'
		e.cost_center='Main - P'
		e.serial_no_=serial_number[1:-1].replace('[','').replace(']','')
		e.parent=d.name
		e.parenttype='Sales Invoice'
		e.parentfield='entries'
		e.save()
		webnotes.conn.commit()
		key={}
		key['invoice_id_id']=d.name
		login.append(key)
		loginObj['status']='200'
		loginObj['invoice']=login
		return loginObj
	else:
		loginObj['status']='401'
		loginObj['error']='invalid token please contact administrator'
		return loginObj
Пример #27
0
def create_in(data,_type='POST'):
	from webnotes.model.doc import Document
	from webnotes.utils import nowdate,add_months
        data1=json.loads(data)	
        auth_key=data1['token']
        invoice_type=data1['invoice_type']
        customer=data1['customer']
        dattime=data1['datetime']
        item_details=data1['item_details']
        login =[]
        loginObj = {}
	amt=0
        qt=0
        srl=''
        cc=''
        zz=''
	#return data
        if len(auth_key[1:-1]) <=0 or len(dattime[1:-1]) <=0 or len(customer[1:-1])<=0 :
                loginObj['status']='401'
                loginObj['error']='Incomplete data to generate Sales Invoice , Please provide token no , Datetime,customer and serial no'
                return loginObj
 	
        for ff in item_details:
                   a=ff['barcode']
                   c="select item_code,warehouse from `tabSerial No` where name='"+a[:-1]+"'"
                   cc=webnotes.conn.sql(c)
		   #webnotes.errprint(c)
		   #webnotes.errprint(cc)
                   amt=cint(amt)+cint(ff['rate'])
                   qt+=1
                   srl+=a[:-2].replace(',','\n')
		   #return cc
                   if cc :
			qr="select name from `tabauth keys` where auth_key='"+auth_key+"'"
			#return qr
			res=webnotes.conn.sql(qr)
			if res :
		           rr="select region from `tabFranchise` where contact_email='"+res[0][0]+"'"
                           r1=webnotes.conn.sql(rr)
			   if r1[0][0]==cc[0][1] :
				#webnotes.errprint("same")
				pass
			   else:
				#webnotes.errprint("different warehouse")
				pass
				
                        zz+="'"+a[:-1].replace(',','')+"',"
                   else:
                   	if invoice_type=='CUSTOMER':
				l = Document('Customer Details',customer)
		                l.customer_name=customer
		                l.save()
		                webnotes.conn.commit()
				for ll in item_details:
				   m = Document('Customer Data')
				   m.serial_no=a[:-1]
		                   m.parent=l.name
		                   m.parenttype='Customer Details'
		                   m.parentfield='customer_data'
			           m.save(new=1)
				   webnotes.conn.commit()			
			qrt="select name from `tabauth keys` where auth_key='"+auth_key+"'"
		        res=webnotes.conn.sql(qrt)
        		net=0
		        if res:
                		a="select name from tabCustomer where name='"+customer+"'"
		                b=webnotes.conn.sql(a)
		                if b:
		                        a=''
		                else:
                		        d = Document('Customer')
                		        d.customer_name=customer
		                        d.name=customer
                		        d.save(new=1)
                		        webnotes.conn.commit()
               		qr="select name from `tabauth keys` where auth_key='"+auth_key+"'"
               		#webnotes.errprint(qr)
			res=webnotes.conn.sql(qr)
			rgn=''
			if res :
		           rr="select region from `tabFranchise` where contact_email='"+res[0][0]+"'"
		           #webnotes.errprint(qr)
                           r1=webnotes.conn.sql(rr,as_list=1)
                           #webnotes.errprint(r1[0][0])			   
                	d = Document('Sales Invoice')
	                d.customer=customer
	                d.customer_name=customer
        	        d.posting_date=dattime[1:-1]
        	        d.due_date=dattime[1:-1]
        	        d.remarks='Invalid QR code'
        	        d.selling_price_list='Standard Selling'
        	        d.currency='INR'
        	        if r1:
        	        	d.territory=r1[0][0]
        	        	d.region=r1[0][0]
        	        d.net_total_export=0
        	        d.grand_total_export=0
        	        d.rounded_total_export=0
        	        d.plc_conversion_rate=1			
        	        from webnotes.utils import nowdate
        	        from accounts.utils import get_fiscal_year
        	        today = nowdate()
        	        d.fiscal_year=get_fiscal_year(today)[0]
        	        d.debit_to=customer[1:-1]+" - P"
        	        d.is_pos=1
        	        d.cash_bank_account='Cash - P'
        	        d.docstatus=1
        	        d.save(new=1)
        	        webnotes.conn.commit()
        	        e=Document('Sales Invoice Item')
		        e.description="Invalid QR code"
		        e.qty='1'
		        e.stock_uom='Nos'
		        e.serial_no_=a[:-1]
		        e.parent=d.name
		        e.parenttype='Sales Invoice'
		        e.parentfield='entries'
		        e.save(new=1)        	        	        
        	        webnotes.conn.commit()
        	        key={}
        	        key['invoice_id']=d.name
        	        login.append(key)
        	        loginObj['status']='200'
        	        loginObj['invoice']=login
        	        return loginObj
                        #loginObj['status']='400'
                        #loginObj['error']='invalid serial no (QR Code) please contact administrator'
                        #return loginObj
        z=zz[:-1]
	u="select distinct item_code from `tabSerial No` where name in ("+z+")"
	s=webnotes.conn.sql(u,as_list=1)
	qty_dict={}
	rate_dict={}
	srl_dict={}
        for key in s:
		qty_dict.setdefault(key[0],0)
		rate_dict.setdefault(key[0],0)  
		srl_dict.setdefault(key[0],'')
        for sss in item_details:
		a=sss['barcode']
                c="select item_code from `tabSerial No` where name='"+a[:-1]+"'"
                cc=webnotes.conn.sql(c)
		d=cc and cc[0][0] or ''
		qty_dict[d]=cint(qty_dict[d])+1
		rate_dict[d]=cint(rate_dict[d])+cint(sss['rate'])
                srl_dict[d]=srl_dict[d]+a[:-1]+"\n"
        if invoice_type=='CUSTOMER':
            	#a="select name from `tabCustomer Details`where name like '"+customer+"-%'"
            	#b=webnotes.conn.sql(a)               
	    	#webnotes.errprint(a)
            	#if b:
                #a=''
            	#else:
		#webnotes.errprint("else "+a)
		l = Document('Customer Details',customer)
                l.customer_name=customer
                l.save()
                webnotes.conn.commit()
		for ll in item_details:
		   m = Document('Customer Data')
		   #.serial_no=ll['barcode']
		   #webnotes.errprint(a[:-1])
	           m.serial_no=a[:-1]
                   #m.start_date=nowdate()
		   m.parent=l.name
                   m.parenttype='Customer Details'
                   m.parentfield='customer_data'
	           m.save(new=1)
		   #webnotes.errprint("before g1")
		   g1="update `tabSerial No` set warehouse='',delivery_date=CURDATE(),status='Delivered',customer='"+customer+"' where name='"+cstr(ll['barcode']).replace(',','')+"'"
                   webnotes.conn.sql(g1)
                   webnotes.conn.commit()
	else:
		for gg in item_details:
		   g=gg['barcode']
	           #webnotes.errprint("in else gg")
		   #webnotes.errprint(g[:-2])
                   g1="update `tabSerial No` set warehouse='',delivery_date=CURDATE(),status='Delivered',customer='"+customer+"' where name='"+g[:-1]+"'"
                   webnotes.conn.sql(g1)
                   webnotes.conn.commit()
	for hh in item_details:
		   h=hh['barcode']
		   g=h[:-2] 
                   i="select item_code from `tabSerial No` where name='"+g+"'"
                   ii=webnotes.conn.sql(i)
        qrt="select name from `tabauth keys` where auth_key='"+auth_key+"'"
        res=webnotes.conn.sql(qrt)
        net=0
        if res:
                a="select name from tabCustomer where name='"+customer+"'"
                #webnotes.errprint(a)
                b=webnotes.conn.sql(a)
                #webnotes.errprint(b)                
                if b:
                        a=''
                else:
                        #webnotes.errprint("else")
                        d = Document('Customer')
                        d.customer_name=customer
                        d.name=customer
                        d.save(new=1)
                        webnotes.conn.commit()
                d = Document('Sales Invoice')
                d.customer=customer
                d.customer_name=customer
                d.posting_date=dattime[1:-1]
                d.due_date=dattime[1:-1]
                d.selling_price_list='Standard Selling'
                d.currency='INR'
                d.territory=r1[0][0]
                d.net_total_export=0
                d.grand_total_export=0
                d.rounded_total_export=0
                d.plc_conversion_rate=1
		d.region=r1[0][0]
                from webnotes.utils import nowdate
                from accounts.utils import get_fiscal_year
                today = nowdate()
                d.fiscal_year=get_fiscal_year(today)[0]
                d.debit_to=customer[1:-1]+" - P"
                d.is_pos=1
                d.cash_bank_account='Cash - P'
                d.save(new=1)
                webnotes.conn.commit()
                for x in qty_dict.keys():
	                e=Document('Sales Invoice Item')
	                e.item_code=x
	                e.item_name=x
	                e.description=x
	                e.qty=qty_dict[x]
	                e.stock_uom='Nos'
	                e.ref_rate=cint(rate_dict[x])/cint(qty_dict[x])
	                e.export_rate=cint(rate_dict[x])/cint(qty_dict[x])
	                e.export_amount=cint(rate_dict[x])
	                e.income_account='Sales - P'
	                e.cost_center='Main - P'
	                e.serial_no_=srl_dict[x]
	                e.parent=d.name
	                e.parenttype='Sales Invoice'
	                e.parentfield='entries'
	                e.save(new=1)
                        net+=cint(rate_dict[x])
			qrs="select warranty_period from tabItem where name='"+x+"'"
			#webnotes.errprint(qrs)
	 		ress=webnotes.conn.sql(qrs)
	 		#webnotes.errprint(ress[0][0])
	 		if ress:
	 			exdt=add_months(cstr(nowdate()),cint(ress[0][0]))
	 		else:
	 			exdt='null'
	 		#webnotes.errprint(cstr(srl_dict[x]))
			#webnotes.errprint(g)
			g2="update `tabSerial No` set warehouse='', warranty_expiry_date='"+cstr(exdt)+"',delivery_date=CURDATE(),status='Delivered',customer='"+customer+"' where name='"+cstr(h[:-1])+"'"
		 	#webnotes.errprint(g2)
			#webnotes.errprint("in x in qty dict")
                        webnotes.conn.sql(g2)
	                webnotes.conn.commit()
                d = Document('Sales Invoice',d.name)
                d.net_total_export=net
		d.net_total=net
                d.grand_total_export=net
                d.rounded_total_export=net
                d.outstanding_amount=net
		d.docstatus=1
                d.save()
                webnotes.conn.commit()
                key={}
                key['invoice_id']=d.name
                login.append(key)
                loginObj['status']='200'
                loginObj['invoice']=login
                return loginObj
        else:
                loginObj['status']='401'
                loginObj['error']='invalid token please contact administrator'
                return loginObj  
Пример #28
0
def import_vouchers(common_values, data, start_idx, import_type):
    from webnotes.model.doc import Document
    from webnotes.model.bean import Bean
    from accounts.utils import get_fiscal_year
    from webnotes.utils.dateutils import parse_date

    messages = []

    def get_account_details(account):
        acc_details = webnotes.conn.sql("""select is_pl_account, 
			master_name from tabAccount where name=%s""",
                                        account,
                                        as_dict=1)
        if not acc_details:
            webnotes.msgprint("%s is not an Account" % account,
                              raise_exception=1)
        return acc_details[0]

    def apply_cost_center_and_against_invoice(detail, d):
        account = get_account_details(detail.account)

        if account.is_pl_account == "Yes":
            detail.cost_center = d.cost_center

        if account.master_name:
            map_fields([
                "against_sales_invoice:against_invoice",
                "against_purhase_invoice:against_voucher",
                "against_journal_voucher:against_jv"
            ], d, detail.fields)

    webnotes.conn.commit()
    try:
        jv = Document("Journal Voucher")

        webnotes.conn.begin()
        for i in xrange(len(data)):
            jv = Document("Journal Voucher")

            d = data[i][0]
            if import_type == "Voucher Import: Two Accounts" and flt(
                    d.get("amount")) == 0:
                webnotes.message_log = ["Amount not specified"]
                raise Exception
            elif import_type == "Voucher Import: Multiple Accounts" and \
               (flt(d.get("total_debit")) == 0 or flt(d.get("total_credit")) == 0):
                webnotes.message_log = [
                    "Total Debit and Total Credit amount can not be zero"
                ]
                raise Exception
            else:
                d.posting_date = parse_date(d.posting_date)
                d.due_date = d.due_date and parse_date(d.due_date) or None

                if d.ref_number:
                    if not d.ref_date:
                        raise webnotes.ValidationError, \
                         """Ref Date is Mandatory if Ref Number is specified"""
                    d.ref_date = parse_date(d.ref_date)

                d.company = common_values.company

                map_fields([
                    "voucher_type", "posting_date", "naming_series",
                    "remarks:user_remark", "ref_number:cheque_no",
                    "ref_date:cheque_date", "is_opening", "due_date", "company"
                ], d, jv.fields)

                jv.fiscal_year = get_fiscal_year(jv.posting_date)[0]

                details = []
                if import_type == "Voucher Import: Two Accounts":
                    map_fields(["amount:total_debit", "amount:total_credit"],
                               d, jv.fields)

                    detail1 = Document("Journal Voucher Detail")
                    detail1.parent = True
                    detail1.parentfield = "entries"
                    map_fields(["debit_account:account", "amount:debit"], d,
                               detail1.fields)
                    apply_cost_center_and_against_invoice(detail1, d)

                    detail2 = Document("Journal Voucher Detail")
                    detail2.parent = True
                    detail2.parentfield = "entries"
                    map_fields(["credit_account:account", "amount:credit"], d,
                               detail2.fields)
                    apply_cost_center_and_against_invoice(detail2, d)

                    details = [detail1, detail2]
                elif import_type == "Voucher Import: Multiple Accounts":
                    map_fields(["total_debit", "total_credit"], d, jv.fields)
                    accounts = data[i][1]
                    for acc in accounts:
                        detail = Document("Journal Voucher Detail")
                        detail.parent = True
                        detail.parentfield = "entries"
                        detail.account = acc
                        detail.debit = flt(accounts[acc]) > 0 and flt(
                            accounts[acc]) or 0
                        detail.credit = flt(
                            accounts[acc]) < 0 and -1 * flt(accounts[acc]) or 0
                        apply_cost_center_and_against_invoice(detail, d)
                        details.append(detail)

                if not details:
                    webnotes.message_log = [
                        """No accounts found. 
						If you entered accounts correctly, please check template once"""
                    ]
                    raise Exception

                doclist = Bean([jv] + details)

                # validate datatype
                from core.page.data_import_tool.data_import_tool import check_record
                for d in doclist:
                    check_record(d.fields, d.parenttype)

                doclist.submit()

                messages.append("""<p style='color: green'>[row #%s] 
					<a href=\"#Form/Journal Voucher/%s\">%s</a> imported</p>""" \
                 % ((start_idx + 1) + i, jv.name, jv.name))
        webnotes.conn.commit()
    except Exception, e:
        webnotes.conn.rollback()
        err_msg = webnotes.message_log and "<br>".join(
            webnotes.message_log) or unicode(e)
        messages.append(
            """<p style='color: red'>[row #%s] %s failed: %s</p>""" %
            ((start_idx + 1) + i, jv.name or "", err_msg or "No message"))
        messages.append(
            "<p style='color: red'>All transactions rolled back</p>")
        webnotes.errprint(webnotes.getTraceback())
        webnotes.message_log = []
Пример #29
0
	def validate_posting_date(self):
		from accounts.utils import get_fiscal_year
		fiscal_year = get_fiscal_year(self.doc.posting_date)[0]
		
		if fiscal_year != self.doc.fiscal_year:
			msgprint(_("Posting date must be in the Selected Fiscal Year"), raise_exception=1)
Пример #30
0
    def test_recurring_invoice(self):
        from webnotes.utils import get_first_day, get_last_day, add_to_date, nowdate, getdate
        from accounts.utils import get_fiscal_year
        today = nowdate()
        base_si = webnotes.bean(copy=test_records[0])
        base_si.doc.fields.update({
            "convert_into_recurring_invoice":
            1,
            "recurring_type":
            "Monthly",
            "notification_email_address":
            "[email protected], [email protected], [email protected]",
            "repeat_on_day_of_month":
            getdate(today).day,
            "posting_date":
            today,
            "fiscal_year":
            get_fiscal_year(today)[0],
            "invoice_period_from_date":
            get_first_day(today),
            "invoice_period_to_date":
            get_last_day(today)
        })

        # monthly
        si1 = webnotes.bean(copy=base_si.doclist)
        si1.insert()
        si1.submit()
        self._test_recurring_invoice(si1, True)

        # monthly without a first and last day period
        si2 = webnotes.bean(copy=base_si.doclist)
        si2.doc.fields.update({
            "invoice_period_from_date":
            today,
            "invoice_period_to_date":
            add_to_date(today, days=30)
        })
        si2.insert()
        si2.submit()
        self._test_recurring_invoice(si2, False)

        # quarterly
        si3 = webnotes.bean(copy=base_si.doclist)
        si3.doc.fields.update({
            "recurring_type":
            "Quarterly",
            "invoice_period_from_date":
            get_first_day(today),
            "invoice_period_to_date":
            get_last_day(add_to_date(today, months=3))
        })
        si3.insert()
        si3.submit()
        self._test_recurring_invoice(si3, True)

        # quarterly without a first and last day period
        si4 = webnotes.bean(copy=base_si.doclist)
        si4.doc.fields.update({
            "recurring_type":
            "Quarterly",
            "invoice_period_from_date":
            today,
            "invoice_period_to_date":
            add_to_date(today, months=3)
        })
        si4.insert()
        si4.submit()
        self._test_recurring_invoice(si4, False)

        # yearly
        si5 = webnotes.bean(copy=base_si.doclist)
        si5.doc.fields.update({
            "recurring_type":
            "Yearly",
            "invoice_period_from_date":
            get_first_day(today),
            "invoice_period_to_date":
            get_last_day(add_to_date(today, years=1))
        })
        si5.insert()
        si5.submit()
        self._test_recurring_invoice(si5, True)

        # yearly without a first and last day period
        si6 = webnotes.bean(copy=base_si.doclist)
        si6.doc.fields.update({
            "recurring_type":
            "Yearly",
            "invoice_period_from_date":
            today,
            "invoice_period_to_date":
            add_to_date(today, years=1)
        })
        si6.insert()
        si6.submit()
        self._test_recurring_invoice(si6, False)

        # change posting date but keep recuring day to be today
        si7 = webnotes.bean(copy=base_si.doclist)
        si7.doc.fields.update({"posting_date": add_to_date(today, days=-1)})
        si7.insert()
        si7.submit()

        # setting so that _test function works
        si7.doc.posting_date = today
        self._test_recurring_invoice(si7, True)
Пример #31
0
def create_material_request(material_requests):
    """	Create indent on reaching reorder level	"""
    mr_list = []
    defaults = webnotes.defaults.get_defaults()
    exceptions_list = []
    from accounts.utils import get_fiscal_year
    current_fiscal_year = get_fiscal_year(nowdate())[0] or defaults.fiscal_year
    for request_type in material_requests:
        for company in material_requests[request_type]:
            try:
                items = material_requests[request_type][company]
                if not items:
                    continue

                mr = [{
                    "doctype": "Material Request",
                    "company": company,
                    "fiscal_year": current_fiscal_year,
                    "transaction_date": nowdate(),
                    "material_request_type": request_type
                }]

                for d in items:
                    item = webnotes.doc("Item", d.item_code)
                    mr.append({
                        "doctype":
                        "Material Request Item",
                        "parenttype":
                        "Material Request",
                        "parentfield":
                        "indent_details",
                        "item_code":
                        d.item_code,
                        "schedule_date":
                        add_days(nowdate(), cint(item.lead_time_days)),
                        "uom":
                        item.stock_uom,
                        "warehouse":
                        d.warehouse,
                        "item_name":
                        item.item_name,
                        "description":
                        item.description,
                        "item_group":
                        item.item_group,
                        "qty":
                        d.reorder_qty,
                        "brand":
                        item.brand,
                    })

                mr_bean = webnotes.bean(mr)
                mr_bean.insert()
                mr_bean.submit()
                mr_list.append(mr_bean)

            except:
                if webnotes.local.message_log:
                    exceptions_list.append([] + webnotes.local.message_log)
                    webnotes.local.message_log = []
                else:
                    exceptions_list.append(webnotes.getTraceback())

    if mr_list:
        if getattr(webnotes.local, "reorder_email_notify", None) is None:
            webnotes.local.reorder_email_notify = cint(
                webnotes.conn.get_value('Stock Settings', None,
                                        'reorder_email_notify'))

        if (webnotes.local.reorder_email_notify):
            send_email_notification(mr_list)

    if exceptions_list:
        notify_errors(exceptions_list)
def execute():
    webnotes.conn.auto_commit_on_many_writes = 1
    item_map = {}
    for item in webnotes.conn.sql("""select * from tabItem""", as_dict=1):
        item_map.setdefault(item.name, item)

    warehouse_map = get_warehosue_map()
    naming_series = "STE"

    for company, default_expense_account, cost_center in webnotes.conn.sql(
        "select name, default_expense_account, cost_center from tabCompany"
    ):
        stock_entry = [
            {
                "doctype": "Stock Entry",
                "naming_series": naming_series,
                "posting_date": nowdate(),
                "posting_time": nowtime(),
                "purpose": "Material Transfer",
                "company": company,
                "remarks": "Material Transfer to activate perpetual inventory",
                "fiscal_year": get_fiscal_year(nowdate())[0],
            }
        ]
        stock_entry_details = []
        for bin in webnotes.conn.sql(
            """select * from tabBin bin where ifnull(item_code, '')!='' 
				and ifnull(warehouse, '') in (%s) and ifnull(actual_qty, 0) != 0
				and (select company from tabWarehouse where name=bin.warehouse)=%s"""
            % (", ".join(["%s"] * len(warehouse_map)), "%s"),
            (warehouse_map.keys() + [company]),
            as_dict=1,
        ):
            item_details = item_map[bin.item_code]
            # new_warehouse = warehouse_map[bin.warehouse].get("fixed_asset_warehouse") \
            # 	if cstr(item_details.is_asset_item) == "Yes" \
            # 	else warehouse_map[bin.warehouse].get("current_asset_warehouse")

            # for vence
            new_warehouse = warehouse_map[bin.warehouse].get("current_asset_warehouse") or warehouse_map[
                bin.warehouse
            ].get("fixed_asset_warehouse")

            if item_details.has_serial_no == "Yes":
                serial_no = "\n".join(
                    [
                        d[0]
                        for d in webnotes.conn.sql(
                            """select name 
					from `tabSerial No` where item_code = %s and warehouse = %s 
					and status in ('Available', 'Sales Returned')""",
                            (bin.item_code, bin.warehouse),
                        )
                    ]
                )
            else:
                serial_no = None

            stock_entry_details.append(
                {
                    "doctype": "Stock Entry Detail",
                    "parentfield": "mtn_details",
                    "s_warehouse": bin.warehouse,
                    "t_warehouse": new_warehouse,
                    "item_code": bin.item_code,
                    "item_name": item_details.item_name,
                    "description": item_details.description,
                    "qty": bin.actual_qty,
                    "transfer_qty": bin.actual_qty,
                    "uom": item_details.stock_uom,
                    "stock_uom": item_details.stock_uom,
                    "conversion_factor": 1,
                    "expense_account": default_expense_account,
                    "cost_center": cost_center,
                    "serial_no": serial_no,
                }
            )

        se = []
        for i, details in enumerate(stock_entry_details):
            se.append(details)
            if (i + 1) % 200 == 0:
                webnotes.bean(stock_entry + se).insert()
                se = []
        if len(se) > 1:
            webnotes.bean(stock_entry + se).insert()

    webnotes.conn.auto_commit_on_many_writes = 0
Пример #33
0
def import_vouchers(common_values, data, start_idx, import_type):
	from webnotes.model.doc import Document
	from webnotes.model.bean import Bean
	from accounts.utils import get_fiscal_year
	from webnotes.utils.dateutils import parse_date
	messages = []
	
	def get_account_details(account):
		acc_details = webnotes.conn.sql("""select is_pl_account, 
			master_name from tabAccount where name=%s""", account, as_dict=1)
		if not acc_details:
			webnotes.msgprint("%s is not an Account" % account, raise_exception=1)
		return acc_details[0]

	def apply_cost_center_and_against_invoice(detail, d):
		account = get_account_details(detail.account)

		if account.is_pl_account=="Yes":
			detail.cost_center = d.cost_center
		
		if account.master_name:
			map_fields(["against_sales_invoice:against_invoice", 
				"against_purhase_invoice:against_voucher", 
				"against_journal_voucher:against_jv"], d, detail.fields)
	
	webnotes.conn.commit()
	try:
		jv = Document("Journal Voucher")
		
		webnotes.conn.begin()
		for i in xrange(len(data)):
			jv = Document("Journal Voucher")
			
			d = data[i][0]
			if import_type == "Voucher Import: Two Accounts" and flt(d.get("amount")) == 0:
				webnotes.message_log = ["Amount not specified"]
				raise Exception
			elif import_type == "Voucher Import: Multiple Accounts" and \
			 		(flt(d.get("total_debit")) == 0 or flt(d.get("total_credit")) == 0):
				webnotes.message_log = ["Total Debit and Total Credit amount can not be zero"]
				raise Exception
			else:
				d.posting_date = parse_date(d.posting_date)
				d.due_date = d.due_date and parse_date(d.due_date) or None
				
				if d.ref_number:
					if not d.ref_date:
						webnotes.msgprint(_("Ref Date is Mandatory if Ref Number is specified"), 
							raise_exception=1)
							
					d.ref_date = parse_date(d.ref_date)
				
				d.company = common_values.company
						
				map_fields(["voucher_type", "posting_date", "naming_series", 
					"remarks:user_remark", "ref_number:cheque_no", "ref_date:cheque_date",
					"is_opening", "due_date", "company"], d, jv.fields)

				jv.fiscal_year = get_fiscal_year(jv.posting_date)[0]

				details = []
				if import_type == "Voucher Import: Two Accounts":
					map_fields(["amount:total_debit", "amount:total_credit"], d, jv.fields)
					
					detail1 = Document("Journal Voucher Detail")
					detail1.parent = True
					detail1.parentfield = "entries"
					map_fields(["debit_account:account","amount:debit"], d, detail1.fields)
					apply_cost_center_and_against_invoice(detail1, d)
		

					detail2 = Document("Journal Voucher Detail")
					detail2.parent = True
					detail2.parentfield = "entries"
					map_fields(["credit_account:account","amount:credit"], d, detail2.fields)
					apply_cost_center_and_against_invoice(detail2, d)
				
					details = [detail1, detail2]
				elif import_type == "Voucher Import: Multiple Accounts":
					map_fields(["total_debit", "total_credit"], d, jv.fields)
					accounts = data[i][1]
					for acc in accounts:
						detail = Document("Journal Voucher Detail")
						detail.parent = True
						detail.parentfield = "entries"
						detail.account = acc
						detail.debit = flt(accounts[acc]) > 0 and flt(accounts[acc]) or 0
						detail.credit = flt(accounts[acc]) < 0 and -1*flt(accounts[acc]) or 0
						apply_cost_center_and_against_invoice(detail, d)
						details.append(detail)
								
				if not details:
					webnotes.message_log = ["""No accounts found. 
						If you entered accounts correctly, please check template once"""]
					raise Exception
					
				doclist = Bean([jv]+details)
				
				# validate datatype
				from core.page.data_import_tool.data_import_tool import check_record
				for d in doclist:
					check_record(d.fields, d.parenttype)
				
				doclist.submit()
			
				messages.append("""<p style='color: green'>[row #%s] 
					<a href=\"#Form/Journal Voucher/%s\">%s</a> imported</p>""" \
					% ((start_idx + 1) + i, jv.name, jv.name))
		webnotes.conn.commit()
	except Exception, e:
		webnotes.conn.rollback()
		err_msg = webnotes.message_log and "<br>".join(webnotes.message_log) or cstr(e)
		messages.append("""<p style='color: red'>[row #%s] %s failed: %s</p>"""
			% ((start_idx + 1) + i, jv.name or "", err_msg or "No message"))
		messages.append("<p style='color: red'>All transactions rolled back</p>")
		webnotes.errprint(webnotes.getTraceback())
		webnotes.message_log = []
Пример #34
0
     "doctype": "Account",
     "account_name": "Test Supplier",
     "parent_account": "Accounts Payable - %s" % abbr,
     "company": company,
     "debit_or_credit": "Credit",
     "is_pl_account": "No",
     "group_or_ledger": "Ledger"
 },
 "journal_voucher": [
     {
         "doctype": "Journal Voucher",
         "voucher_type": "Journal Entry",
         "naming_series": "JV",
         "posting_date": nowdate(),
         "remark": "Test Journal Voucher",
         "fiscal_year": get_fiscal_year(nowdate())[0],
         "company": company
     },
     {
         "doctype": "Journal Voucher Detail",
         "parentfield": "entries",
         "account": "Test Expense - %s" % abbr,
         "debit": 5000,
         "cost_center": "Default CC Ledger - %s" % abbr,
     },
     {
         "doctype": "Journal Voucher Detail",
         "parentfield": "entries",
         "account": "Test Supplier - %s" % abbr,
         "credit": 5000,
     },
Пример #35
0
def create_material_request(material_requests):
	"""	Create indent on reaching reorder level	"""
	mr_list = []
	defaults = webnotes.defaults.get_defaults()
	exceptions_list = []
	from accounts.utils import get_fiscal_year
	current_fiscal_year = get_fiscal_year(nowdate())[0] or defaults.fiscal_year
	for request_type in material_requests:
		for company in material_requests[request_type]:
			try:
				items = material_requests[request_type][company]
				if not items:
					continue

				mr = [{
					"doctype": "Material Request",
					"company": company,
					"fiscal_year": current_fiscal_year,
					"transaction_date": nowdate(),
					"material_request_type": request_type
				}]

				for d in items:
					item = webnotes.doc("Item", d.item_code)
					mr.append({
						"doctype": "Material Request Item",
						"parenttype": "Material Request",
						"parentfield": "indent_details",
						"item_code": d.item_code,
						"schedule_date": add_days(nowdate(),cint(item.lead_time_days)),
						"uom":	item.stock_uom,
						"warehouse": d.warehouse,
						"item_name": item.item_name,
						"description": item.description,
						"item_group": item.item_group,
						"qty": d.reorder_qty,
						"brand": item.brand,
					})

				mr_bean = webnotes.bean(mr)
				mr_bean.insert()
				mr_bean.submit()
				mr_list.append(mr_bean)

			except:
				if webnotes.local.message_log:
					exceptions_list.append([] + webnotes.local.message_log)
					webnotes.local.message_log = []
				else:
					exceptions_list.append(webnotes.getTraceback())

	if mr_list:
		if getattr(webnotes.local, "reorder_email_notify", None) is None:
			webnotes.local.reorder_email_notify = cint(webnotes.conn.get_value('Stock Settings', None,
				'reorder_email_notify'))

		if(webnotes.local.reorder_email_notify):
			send_email_notification(mr_list)

	if exceptions_list:
		notify_errors(exceptions_list)
Пример #36
0
def import_vouchers(common_values, data, start_idx, import_type):
	from webnotes.model.doc import Document
	from webnotes.model.doclist import DocList
	from webnotes.model.code import get_obj
	from accounts.utils import get_fiscal_year
	from webnotes.utils.dateutils import parse_date

	messages = []
		
	def get_account_details(account):
		acc_details = webnotes.conn.sql("""select is_pl_account, 
			master_name from tabAccount where name=%s""", account, as_dict=1)
		if not acc_details:
			webnotes.msgprint("%s is not an Account" % account, raise_exception=1)
		return acc_details[0]

	def apply_cost_center_and_against_invoice(detail, d):
		account = get_account_details(detail.account)

		if account.is_pl_account=="Yes":
			detail.cost_center = d.cost_center
		
		if account.master_name:
			map_fields(["against_sales_invoice:against_invoice", 
				"against_purhase_invoice:against_voucher", 
				"against_journal_voucher:against_jv"], d, detail.fields)
	
	webnotes.conn.commit()
	for i in xrange(len(data)):
		d = data[i][0]
		jv = webnotes.DictObj()

		try:
			d.posting_date = parse_date(d.posting_date)
			d.due_date = d.due_date and parse_date(d.due_date) or None
			
			if d.ref_number:
				if not d.ref_date:
					raise webnotes.ValidationError, \
						"""Ref Date is Mandatory if Ref Number is specified"""
				d.ref_date = parse_date(d.ref_date)
				
			d.company = common_values.company
						
			jv = Document("Journal Voucher")
			map_fields(["voucher_type", "posting_date", "naming_series", "remarks:user_remark",
				"ref_number:cheque_no", "ref_date:cheque_date", "is_opening",
				"amount:total_debit", "amount:total_credit", "due_date", "company"], d, jv.fields)

			jv.fiscal_year = get_fiscal_year(jv.posting_date)[0]

			details = []
			if import_type == "Voucher Import: Two Accounts":
				detail1 = Document("Journal Voucher Detail")
				detail1.parent = True
				detail1.parentfield = "entries"
				map_fields(["debit_account:account","amount:debit"], d, detail1.fields)
				apply_cost_center_and_against_invoice(detail1, d)
		

				detail2 = Document("Journal Voucher Detail")
				detail2.parent = True
				detail2.parentfield = "entries"
				map_fields(["credit_account:account","amount:credit"], d, detail2.fields)
				apply_cost_center_and_against_invoice(detail2, d)
				
				details = [detail1, detail2]
			elif import_type == "Voucher Import: Multiple Accounts":
				accounts = data[i][1]
				for acc in accounts:
					detail = Document("Journal Voucher Detail")
					detail.parent = True
					detail.parentfield = "entries"
					detail.account = acc
					detail.debit = flt(accounts[acc]) > 0 and flt(accounts[acc]) or 0
					detail.credit = flt(accounts[acc]) < 0 and -1*flt(accounts[acc]) or 0
					apply_cost_center_and_against_invoice(detail, d)
					details.append(detail)
								
			if not details:
				messages.append("""<p style='color: red'>No accounts found. 
					If you entered accounts correctly, please check template once</p>""")
				return
			webnotes.conn.begin()
			doclist = DocList([jv]+details)
			doclist.submit()
			webnotes.conn.commit()
			
			messages.append("""<p style='color: green'>[row #%s] 
				<a href=\"#Form/Journal Voucher/%s\">%s</a> imported</p>""" \
				% ((start_idx + 1) + i, jv.name, jv.name))
			
		except Exception, e:
			webnotes.conn.rollback()
			err_msg = webnotes.message_log and webnotes.message_log[0] or unicode(e)
			messages.append("<p style='color: red'>[row #%s] %s failed: %s</p>" \
				% ((start_idx + 1) + i, jv.name or "", err_msg or "No message"))
			webnotes.errprint(webnotes.getTraceback())

		webnotes.message_log = []
Пример #37
0
    def test_recurring_invoice(self):
        from webnotes.utils import get_first_day, get_last_day, add_to_date, nowdate, getdate
        from accounts.utils import get_fiscal_year

        today = nowdate()
        base_si = webnotes.bean(copy=test_records[0])
        base_si.doc.fields.update(
            {
                "convert_into_recurring_invoice": 1,
                "recurring_type": "Monthly",
                "notification_email_address": "[email protected], [email protected], [email protected]",
                "repeat_on_day_of_month": getdate(today).day,
                "posting_date": today,
                "fiscal_year": get_fiscal_year(today)[0],
                "invoice_period_from_date": get_first_day(today),
                "invoice_period_to_date": get_last_day(today),
            }
        )

        # monthly
        si1 = webnotes.bean(copy=base_si.doclist)
        si1.insert()
        si1.submit()
        self._test_recurring_invoice(si1, True)

        # monthly without a first and last day period
        si2 = webnotes.bean(copy=base_si.doclist)
        si2.doc.fields.update(
            {"invoice_period_from_date": today, "invoice_period_to_date": add_to_date(today, days=30)}
        )
        si2.insert()
        si2.submit()
        self._test_recurring_invoice(si2, False)

        # quarterly
        si3 = webnotes.bean(copy=base_si.doclist)
        si3.doc.fields.update(
            {
                "recurring_type": "Quarterly",
                "invoice_period_from_date": get_first_day(today),
                "invoice_period_to_date": get_last_day(add_to_date(today, months=3)),
            }
        )
        si3.insert()
        si3.submit()
        self._test_recurring_invoice(si3, True)

        # quarterly without a first and last day period
        si4 = webnotes.bean(copy=base_si.doclist)
        si4.doc.fields.update(
            {
                "recurring_type": "Quarterly",
                "invoice_period_from_date": today,
                "invoice_period_to_date": add_to_date(today, months=3),
            }
        )
        si4.insert()
        si4.submit()
        self._test_recurring_invoice(si4, False)

        # yearly
        si5 = webnotes.bean(copy=base_si.doclist)
        si5.doc.fields.update(
            {
                "recurring_type": "Yearly",
                "invoice_period_from_date": get_first_day(today),
                "invoice_period_to_date": get_last_day(add_to_date(today, years=1)),
            }
        )
        si5.insert()
        si5.submit()
        self._test_recurring_invoice(si5, True)

        # yearly without a first and last day period
        si6 = webnotes.bean(copy=base_si.doclist)
        si6.doc.fields.update(
            {
                "recurring_type": "Yearly",
                "invoice_period_from_date": today,
                "invoice_period_to_date": add_to_date(today, years=1),
            }
        )
        si6.insert()
        si6.submit()
        self._test_recurring_invoice(si6, False)

        # change posting date but keep recuring day to be today
        si7 = webnotes.bean(copy=base_si.doclist)
        si7.doc.fields.update({"posting_date": add_to_date(today, days=-1)})
        si7.insert()
        si7.submit()

        # setting so that _test function works
        si7.doc.posting_date = today
        self._test_recurring_invoice(si7, True)
Пример #38
0
    def insert_purchase_request(self):
        items_to_be_requested = self.get_requested_items()

        from accounts.utils import get_fiscal_year
        fiscal_year = get_fiscal_year(nowdate())[0]

        purchase_request_list = []
        if items_to_be_requested:
            for item in items_to_be_requested:
                item_wrapper = webnotes.bean("Item", item)
                pr_doclist = [{
                    "doctype": "Material Request",
                    "__islocal": 1,
                    "naming_series": "IDT",
                    "transaction_date": nowdate(),
                    "status": "Draft",
                    "company": self.doc.company,
                    "fiscal_year": fiscal_year,
                    "requested_by": webnotes.session.user,
                    "material_request_type": "Purchase"
                }]
                for sales_order, requested_qty in items_to_be_requested[
                        item].items():
                    pr_doclist.append({
                        "doctype":
                        "Material 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":
                        requested_qty,
                        "schedule_date":
                        add_days(nowdate(),
                                 cint(item_wrapper.doc.lead_time_days)),
                        "warehouse":
                        self.doc.purchase_request_for_warehouse,
                        "sales_order_no":
                        sales_order
                        if sales_order != "No Sales Order" else None
                    })

                pr_wrapper = webnotes.bean(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/Material Request/%s" target="_blank">%s</a>""" % \
                 (p, p) for p in purchase_request_list]
                msgprint("Material Request(s) created: \n%s" %
                         "\n".join(pur_req))
        else:
            msgprint(_("Nothing to request"))
Пример #39
0
	"test_cost_center": {
		"doctype": "Cost Center",
		"cost_center_name": "Test Cost Center",
		"parent_cost_center": "Root - %s" % abbr,
		"company_name": company,
		"group_or_ledger": "Ledger",
		"company_abbr": abbr
	},
	"journal_voucher": [
		{
			"doctype": "Journal Voucher",
			"voucher_type": "Journal Entry",
			"naming_series": "JV",
			"posting_date": nowdate(),
			"remark": "Test Journal Voucher",
			"fiscal_year": get_fiscal_year(nowdate())[0],
			"company": company
		},
		{
			"doctype": "Journal Voucher Detail",
			"parentfield": "entries",
			"account": "Test Expense - %s" % abbr,
			"debit": 5000,
			"cost_center": "Test Cost Center - %s" % abbr,
		},
		{
			"doctype": "Journal Voucher Detail",
			"parentfield": "entries",
			"account": "Test Supplier - %s" % abbr,
			"credit": 5000,
		},
Пример #40
0
	def set_missing_values(self, for_validate=False):
		for fieldname in ["posting_date", "transaction_date"]:
			if not self.doc.fields.get(fieldname) and self.meta.get_field(fieldname):
				self.doc.fields[fieldname] = today()
				if not self.doc.fiscal_year:
					self.doc.fiscal_year = get_fiscal_year(self.doc.fields[fieldname])[0]
Пример #41
0
def set_stock_balance_as_per_serial_no(item_code=None, posting_date=None, posting_time=None,
	 	fiscal_year=None):
	from webnotes.utils import flt, cstr
	from webnotes.model.doc import Document
	from stock.utils import update_bin
	from stock.stock_ledger import update_entries_after
	from accounts.utils import get_fiscal_year
	
	if not posting_date: posting_date = nowdate()
	if not posting_time: posting_time = nowtime()
	if not fiscal_year: fiscal_year = get_fiscal_year(posting_date)[0]
	
	condition = " and item.name='%s'" % item_code.replace("'", "\'") if item_code else ""
		
	bin = webnotes.conn.sql("""select bin.item_code, bin.warehouse, bin.actual_qty, item.stock_uom 
		from `tabBin` bin, tabItem item 
		where bin.item_code = item.name and item.has_serial_no = 'Yes' %s""" % condition)

	for d in bin:
		serial_nos = webnotes.conn.sql("""select count(name) from `tabSerial No` 
			where item_code=%s and warehouse=%s and status = 'Available' and docstatus < 2""", (d[0], d[1]))

		if serial_nos and flt(serial_nos[0][0]) != flt(d[2]):
			print d[0], d[1], d[2], serial_nos[0][0]

		sle = webnotes.conn.sql("""select valuation_rate, company from `tabStock Ledger Entry`
			where item_code = %s and warehouse = %s and ifnull(is_cancelled, 'No') = 'No' 
			order by posting_date desc limit 1""", (d[0], d[1]))

		sl_entries = {
			'doctype'					: 'Stock Ledger Entry',
			'item_code'					: d[0],
			'warehouse'					: d[1],
			'transaction_date'	 		: nowdate(),
			'posting_date'				: posting_date,
			'posting_time'			 	: posting_time,
			'voucher_type'			 	: 'Stock Reconciliation (Manual)',
			'voucher_no'				: '',
			'voucher_detail_no'			: '',
			'actual_qty'				: flt(serial_nos[0][0]) - flt(d[2]),
			'stock_uom'					: d[3],
			'incoming_rate'				: sle and flt(serial_nos[0][0]) > flt(d[2]) and flt(sle[0][0]) or 0,
			'company'					: sle and cstr(sle[0][1]) or 0,
			'fiscal_year'				: fiscal_year,
			'is_cancelled'			 	: 'No',
			'batch_no'					: '',
			'serial_no'					: ''
		}
		
		sle = Document(fielddata=sl_entries)
		sle = sle.insert()
		
		args = sl_entries.copy()
		args.update({
			"sle_id": sle.name,
			"is_amended": 'No'
		})
		
		update_bin(args)
		update_entries_after({
			"item_code": d[0],
			"warehouse": d[1],
			"posting_date": posting_date,
			"posting_time": posting_time
		})