def getchildren(name, childtype, field='', parenttype='', from_doctype=0, prefix='tab'): import webnotes from webnotes.model.doclist import DocList condition = "" values = [] if field: condition += ' and parentfield=%s ' values.append(field) if parenttype: condition += ' and parenttype=%s ' values.append(parenttype) dataset = webnotes.conn.sql("""select * from `%s%s` where parent=%s %s order by idx""" \ % (prefix, childtype, "%s", condition), tuple([name]+values)) desc = webnotes.conn.get_description() l = DocList() for i in dataset: d = Document() d.doctype = childtype d._load_values(i, desc) l.append(d) return l
def savedocs(): """save / submit / cancel / update doclist""" try: from webnotes.model.doclist import DocList form = webnotes.form_dict doclist = DocList() doclist.from_compressed(form.get('docs'), form.get('docname')) # action action = form.get('action') if action=='Update': action='update_after_submit' getattr(doclist, action.lower())() # update recent documents webnotes.user.update_recent(doclist.doc.doctype, doclist.doc.name) # send updated docs webnotes.response['saved'] = '1' webnotes.response['main_doc_name'] = doclist.doc.name webnotes.response['docname'] = doclist.doc.name webnotes.response['docs'] = [doclist.doc] + doclist.children except Exception, e: webnotes.msgprint('Did not save') webnotes.errprint(webnotes.utils.getTraceback()) raise e
def get(dt, dn='', with_children=1, from_controller=0, prefix='tab'): """ Returns a doclist containing the main record and all child records """ import webnotes import webnotes.model from webnotes.model.doclist import DocList dn = dn or dt # load the main doc doc = Document(dt, dn, prefix=prefix) if dt == 'Page' and webnotes.session['user'] == 'Guest': check_page_perm(doc) if not with_children: # done return DocList([ doc, ]) # get all children types tablefields = webnotes.model.meta.get_table_fields(dt) # load chilren doclist = DocList([ doc, ]) for t in tablefields: doclist += getchildren(doc.name, t[0], t[1], dt, prefix=prefix) return doclist
def getchildren(name, childtype, field='', parenttype='', from_doctype=0, prefix='tab'): import webnotes from webnotes.model.doclist import DocList tmp = '' if field: tmp = ' and parentfield="%s" ' % field if parenttype: tmp = ' and parenttype="%s" ' % parenttype dataset = webnotes.conn.sql("select * from `%s%s` where parent='%s' %s order by idx" \ % (prefix, childtype, name, tmp)) desc = webnotes.conn.get_description() l = DocList() for i in dataset: d = Document() d.doctype = childtype d._load_values(i, desc) l.append(d) return l
def rewrite_pages(self): """rewrite all web pages""" import webnotes from webnotes.model.doclist import DocList from webnotes.model.code import get_obj # rewrite all web pages for name in webnotes.conn.sql( """select name, modified from `tabWeb Page` where docstatus=0"""): DocList('Web Page', name[0]).save() webnotes.conn.set_value('Web Page', name[0], 'modified', name[1]) # rewrite all blog pages for name in webnotes.conn.sql("""select name, modified from `tabBlog` where docstatus=0 and ifnull(published,0)=1"""): DocList('Blog', name[0]).save() webnotes.conn.set_value('Blog', name[0], 'modified', name[1]) from webnotes.cms.make import make_web_core make_web_core() get_obj('Page', 'blog').write_cms_page(force=True) get_obj('Page', 'Login Page').write_cms_page(force=True) webnotes.msgprint('Rebuilt all blogs and pages')
def savedocs(): try: from webnotes.model.doclist import DocList form = webnotes.form_dict doclist = DocList() doclist.from_compressed(form.get('docs'), form.get('docname')) # action action = form.get('action') if action == 'Update': action = 'update_after_submit' getattr(doclist, action.lower())() # update recent documents webnotes.user.update_recent(doclist.doc.doctype, doclist.doc.name) # send updated docs webnotes.response['saved'] = '1' webnotes.response['main_doc_name'] = doclist.doc.name webnotes.response['docname'] = doclist.doc.name webnotes.response['docs'] = [doclist.doc] + doclist.children except Exception, e: webnotes.msgprint('Did not save') webnotes.errprint(webnotes.utils.getTraceback()) raise e
def testFailAssert(self): if docnotok: with self.assertRaises(Exception) as context: d = DocList() d.doc = docnotok[0] d.children = None d.doc.fields['__islocal']=1 d.save(1)
def testInsert(self): d = DocList() count_before = flt(sql("select count(*) from tab"+_doctype)[0][0]) if docok: for i in docok: d.doc = i d.children = None d.doc.fields['__islocal']=1 d.save(1) count_after = flt(sql("select count(*) from tab"+_doctype)[0][0]) self.assertTrue(count_before+len(docok)==count_after)
def cancel_packing_slips(self): """ Cancel submitted packing slips related to this delivery note """ res = webnotes.conn.sql("""\ SELECT name, count(*) FROM `tabPacking Slip` WHERE delivery_note = %s AND docstatus = 1 """, self.doc.name) if res and res[0][1]>0: from webnotes.model.doclist import DocList for r in res: ps = DocList(dt='Packing Slip', dn=r[0]) ps.cancel() webnotes.msgprint("%s Packing Slip(s) Cancelled" % res[0][1])
def test_inclusive_rate_validations(self): doclist = [] + [d.copy() for d in sales_invoice_doclist] doclist[1]["export_rate"] = 62.5 doclist[2]["export_rate"] = 191 for i in [3, 5, 6, 7, 8, 9]: doclist[i]["included_in_print_rate"] = 1 # tax type "Actual" cannot be inclusive self.assertRaises(webnotes.ValidationError, webnotes.insert, DocList(doclist)) doclist[3]["included_in_print_rate"] = 0 # taxes above included type 'On Previous Row Total' should also be included self.assertRaises(webnotes.ValidationError, webnotes.insert, DocList(doclist))
def run_purchase_receipt_test(self, purchase_receipt, debit_account, credit_account, stock_value): from webnotes.model.doclist import DocList dl = webnotes.insert(DocList(purchase_receipt)) from controllers.tax_controller import TaxController tax_controller = TaxController(dl.doc, dl.doclist) tax_controller.item_table_field = "purchase_receipt_details" tax_controller.calculate_taxes_and_totals() dl.doc = tax_controller.doc dl.doclist = tax_controller.doclist dl.submit() dl.load_from_db() gle = webnotes.conn.sql( """select account, ifnull(debit, 0), ifnull(credit, 0) from `tabGL Entry` where voucher_no = %s""", dl.doclist[0].name) gle_map = dict(((entry[0], entry) for entry in gle)) self.assertEquals(gle_map[debit_account], (debit_account, stock_value, 0.0)) self.assertEquals(gle_map[credit_account], (credit_account, 0.0, stock_value))
def test_bom(self): gc_wrapper = webnotes.insert(DocList(base_bom_grandchild)) gc_wrapper.submit() bom_child = copy.deepcopy(base_bom_child) bom_child[2]["bom_no"] = gc_wrapper.doc.name child_wrapper = webnotes.insert(DocList(bom_child)) child_wrapper.submit() bom_fg = copy.deepcopy(base_bom_fg) bom_fg[4]["bom_no"] = child_wrapper.doc.name fg_wrapper = webnotes.insert(DocList(bom_fg)) fg_wrapper.load_from_db() self.check_bom_cost(fg_wrapper) self.check_flat_bom(fg_wrapper, child_wrapper, gc_wrapper)
def sort_fields(doclist): """sort on basis of previous_field""" from webnotes.model.doclist import DocList newlist = DocList([]) pending = filter(lambda d: d.doctype == 'DocField', doclist) maxloops = 20 while (pending and maxloops > 0): maxloops -= 1 for d in pending[:]: if d.previous_field: # field already added for n in newlist: if n.fieldname == d.previous_field: newlist.insert(newlist.index(n) + 1, d) pending.remove(d) break else: newlist.append(d) pending.remove(d) # recurring at end if pending: newlist += pending # renum idx = 1 for d in newlist: d.idx = idx idx += 1 doclist.get({"doctype": ["!=", "DocField"]}).extend(newlist)
def get(dt, dn='', with_children=1, from_get_obj=0, prefix='tab'): """ Returns a doclist containing the main record and all child records """ import webnotes import webnotes.model from webnotes.model.doclist import DocList dn = dn or dt # load the main doc doc = Document(dt, dn, prefix=prefix) # check permission - for doctypes, pages if (dt in ('DocType', 'Page', 'Control Panel', 'Search Criteria')) or ( from_get_obj and webnotes.session.get('user') != 'Guest'): if dt == 'Page' and webnotes.session['user'] == 'Guest': check_page_perm(doc) else: if not doc.check_perm(): webnotes.response['403'] = 1 raise webnotes.ValidationError, '[WNF] No read permission for %s %s' % ( dt, dn) if not with_children: # done return DocList([ doc, ]) # get all children types tablefields = webnotes.model.meta.get_table_fields(dt) # load chilren doclist = DocList([ doc, ]) for t in tablefields: doclist += getchildren(doc.name, t[0], t[1], dt, prefix=prefix) # import report_builder code if not from_get_obj: get_report_builder_code(doc) return doclist
def create_custom_field(fld): fld.update({ "doctype": "Custom Field", "dt": "Stock Entry", "print_hide": 1, "permlevel": 0 }) from webnotes.model.doclist import DocList webnotes.insert(DocList([fld]))
def test_bom_validation(self): # show throw error bacause bom no missing for sub-assembly item bom_fg = copy.deepcopy(base_bom_fg) self.assertRaises(webnotes.ValidationError, webnotes.insert, DocList(bom_fg)) # main item is not a manufacturing item bom_fg = copy.deepcopy(base_bom_fg) bom_fg[0]["item"] = "Home Desktop 200" bom_fg.pop(4) self.assertRaises(webnotes.ValidationError, webnotes.insert, DocList(bom_fg)) # operation no mentioed in material table not matching with operation table bom_fg = copy.deepcopy(base_bom_fg) bom_fg.pop(4) bom_fg[2]["operation_no"] = 2 self.assertRaises(webnotes.ValidationError, webnotes.insert, DocList(bom_fg))
def sort_fields(doclist): """sort on basis of previous_field""" from webnotes.model.doclist import DocList newlist = DocList([]) pending = filter(lambda d: d.doctype=='DocField', doclist) maxloops = 20 while (pending and maxloops>0): maxloops -= 1 for d in pending[:]: if d.previous_field: # field already added for n in newlist: if n.fieldname==d.previous_field: newlist.insert(newlist.index(n)+1, d) pending.remove(d) break else: newlist.append(d) pending.remove(d) # recurring at end if pending: newlist += pending # renum idx = 1 for d in newlist: d.idx = idx idx += 1 doclist.get({"doctype":["!=", "DocField"]}).extend(newlist)
def testFailAssert(self): if docnotok: with self.assertRaises(Exception) as context: d = DocList() d.doc = docnotok[0] d.children = None d.doc.fields['__islocal'] = 1 d.save(1)
def test_purchase_invoice_having_zero_amount_items(self): from webnotes.model.doclist import DocList sample_purchase_invoice_doclist = [] + purchase_invoice_doclist # set rate and amount as 0 sample_purchase_invoice_doclist[1]["import_rate"] = 0 sample_purchase_invoice_doclist[2]["import_rate"] = 0 controller = webnotes.insert(DocList(sample_purchase_invoice_doclist)) controller.load_from_db() from controllers.tax_controller import TaxController tax_controller = TaxController(controller.doc, controller.doclist) tax_controller.item_table_field = "entries" tax_controller.calculate_taxes_and_totals() controller.doc = tax_controller.doc controller.doclist = tax_controller.doclist controller.save() controller.load_from_db() dl = controller.doclist # test net total self.assertEqual(dl[0].net_total, 0) # test tax amounts and totals expected_values = [ ["Shipping Charges - %s" % abbr, 100, 100], ["Customs Duty - %s" % abbr, 0, 100], ["Excise Duty - %s" % abbr, 0, 100], ["Education Cess - %s" % abbr, 0, 100], ["S&H Education Cess - %s" % abbr, 0, 100], ["CST - %s" % abbr, 2, 102], ["VAT - Test - %s" % abbr, 0, 102], ["Discount - %s" % abbr, -10.2, 91.8], ] for i, tax in enumerate(dl.get({"parentfield": "purchase_tax_details"})): # print tax.account_head, tax.tax_amount, tax.total 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]) # test item tax amount expected_values = [["Home Desktop 100", 0], ["Home Desktop 200", 0]] for i, item in enumerate( dl.get({"parentfield": "purchase_invoice_items"})): self.assertEqual(item.item_code, expected_values[i][0]) self.assertEqual(item.item_tax_amount, expected_values[i][1])
def runserverobj(): """ Run server objects """ import webnotes.model.code from webnotes.model.doclist import DocList from webnotes.utils import cint form = webnotes.form doclist = None method = form.getvalue('method') arg = form.getvalue('arg') dt = form.getvalue('doctype') dn = form.getvalue('docname') if dt: # not called from a doctype (from a page) if not dn: dn = dt # single so = webnotes.model.code.get_obj(dt, dn) else: doclist = DocList() doclist.from_compressed(form.getvalue('docs'), dn) so = doclist.make_obj() check_guest_access(so.doc) if so: r = webnotes.model.code.run_server_obj(so, method, arg) if r: #build output as csv if cint(webnotes.form.getvalue('as_csv')): make_csv_output(r, so.doc.doctype) else: webnotes.response['message'] = r webnotes.response['docs'] =[so.doc] + so.doclist
def from_cache(doctype, processed): """ load doclist from cache. sets flag __from_cache in first doc of doclist if loaded from cache""" # from memory if doctype_cache and not processed and doctype in doctype_cache: return doctype_cache[doctype] doclist = webnotes.cache().get_value(cache_name(doctype, processed)) if doclist: from webnotes.model.doclist import DocList doclist = DocList( [webnotes.model.doc.Document(fielddata=d) for d in doclist]) doclist[0].fields["__from_cache"] = 1 return doclist
def run_purchase_receipt_test(self, purchase_receipt, debit_account, credit_account, stock_value): from webnotes.model.doclist import DocList dl = webnotes.insert(DocList(purchase_receipt)) dl.submit() dl.load_from_db() gle = webnotes.conn.sql( """select account, ifnull(debit, 0), ifnull(credit, 0) from `tabGL Entry` where voucher_no = %s""", dl.doclist[0].name) gle_map = dict(((entry[0], entry) for entry in gle)) self.assertEquals(gle_map[debit_account], (debit_account, stock_value, 0.0)) self.assertEquals(gle_map[credit_account], (credit_account, 0.0, stock_value))
def testInsert(self): d = DocList() count_before = flt(sql("select count(*) from tab" + _doctype)[0][0]) if docok: for i in docok: d.doc = i d.children = None d.doc.fields['__islocal'] = 1 d.save(1) count_after = flt(sql("select count(*) from tab" + _doctype)[0][0]) self.assertTrue(count_before + len(docok) == count_after)
def test_purchase_invoice(self): from webnotes.model.doclist import DocList controller = webnotes.insert(DocList(purchase_invoice_doclist)) controller.load_from_db() from controllers.tax_controller import TaxController tax_controller = TaxController(controller.doc, controller.doclist) tax_controller.item_table_field = "entries" tax_controller.calculate_taxes_and_totals() controller.doc = tax_controller.doc controller.doclist = tax_controller.doclist controller.save() controller.load_from_db() dl = controller.doclist # test net total self.assertEqual(dl[0].net_total, 1250) # test tax amounts and totals 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(dl.get({"parentfield": "purchase_tax_details"})): # print tax.account_head, tax.tax_amount, tax.total 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]) # test item tax amount expected_values = [["Home Desktop 100", 90], ["Home Desktop 200", 135]] for i, item in enumerate( dl.get({"parentfield": "purchase_invoice_items"})): self.assertEqual(item.item_code, expected_values[i][0]) self.assertEqual(item.item_tax_amount, expected_values[i][1])
def sort_fields(doclist): """sort on basis of previous_field""" from webnotes.model.doclist import DocList newlist = DocList([]) pending = doclist.get({"doctype":"DocField"}) if doclist[0].get("_idx"): for fieldname in json.loads(doclist[0].get("_idx")): d = doclist.get({"fieldname": fieldname}) if d: newlist.append(d[0]) pending.remove(d[0]) else: maxloops = 20 while (pending and maxloops>0): maxloops -= 1 for d in pending[:]: if d.previous_field: # field already added for n in newlist: if n.fieldname==d.previous_field: newlist.insert(newlist.index(n)+1, d) pending.remove(d) break else: newlist.append(d) pending.remove(d) # recurring at end if pending: newlist += pending # renum idx = 1 for d in newlist: d.idx = idx idx += 1 doclist.get({"doctype":["!=", "DocField"]}).extend(newlist)
def save_pages(): """save all web pages, blogs to create content""" query_map = { 'Web Page': """select name from `tabWeb Page` where docstatus=0""", 'Blog': """\ select name from `tabBlog` where docstatus = 0 and ifnull(published, 0) = 1""", 'Item': """\ select name from `tabItem` where docstatus = 0 and ifnull(show_in_website, 0) = 1""", } import webnotes from webnotes.model.doclist import DocList import webnotes.modules.patch_handler for dt in query_map: for result in webnotes.conn.sql(query_map[dt], as_dict=1): try: DocList(dt, result['name'].encode('utf-8')).save() except Exception, e: webnotes.modules.patch_handler.log(unicode(e))
def atest_gl_entries(self): from webnotes.model.doclist import DocList controller = webnotes.insert(DocList(purchase_invoice_doclist)) from controllers.tax_controller import TaxController tax_controller = TaxController(controller.doc, controller.doclist) tax_controller.item_table_field = "entries" tax_controller.calculate_taxes_and_totals() controller.doc = tax_controller.doc controller.doclist = tax_controller.doclist controller.submit() controller.load_from_db() dl = controller.doclist expected_values = { "East Wind Inc. - %s" % abbr: [0, 1512.30], "Shipping Charges - %s" % abbr: [100, 0], "Excise Duty - %s" % abbr: [140, 0], "Education Cess - %s" % abbr: [2.8, 0], "S&H Education Cess - %s" % abbr: [1.4, 0], "CST - %s" % abbr: [29.88, 0], "VAT - Test - %s" % abbr: [156.25, 0], "Discount - %s" % abbr: [0, 168.03], "Stock Received But Not Billed - %s" % abbr: [1475, 0], "Expenses Included In Valuation - %s" % abbr: [0, 225] } 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"], expected_values.get(d['account'])[0]) self.assertEqual(d["credit"], expected_values.get(d['account'])[1])
def runserverobj(): """ Run server objects """ import webnotes.model.code from webnotes.model.doclist import DocList from webnotes.utils import cint form = webnotes.form doclist = None method = form.getvalue('method') arg = form.getvalue('arg') dt = form.getvalue('doctype') dn = form.getvalue('docname') if dt: # not called from a doctype (from a page) if not dn: dn = dt # single so = webnotes.model.code.get_obj(dt, dn) else: doclist = DocList() doclist.from_compressed(form.getvalue('docs'), dn) so = doclist.make_obj() doclist.check_if_latest() check_guest_access(so.doc) if so: r = webnotes.model.code.run_server_obj(so, method, arg) if r: #build output as csv if cint(webnotes.form.getvalue('as_csv')): make_csv_output(r, so.doc.doctype) else: webnotes.response['message'] = r webnotes.response['docs'] = [so.doc] + so.doclist
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() try: webnotes.conn.begin() for i in xrange(len(data)): 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 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", "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 = DocList([jv] + details) 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 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")) messages.append( "<p style='color: red'>All transactions rolled back</p>") webnotes.errprint(webnotes.getTraceback()) webnotes.message_log = []
def test_usd_sales_invoice_with_inclusive_tax(self): # print # print "-"*80 # print "test_usd_sales_invoice_with_inclusive_tax" # print "-"*80 # Note: below values were obtained through manual calculation and verified by test doclist = [ # parent { "doctype": "Sales Invoice", "debit_to": "West Wind Inc. - %s" % abbr, "customer_name": "West Wind Inc.", "naming_series": "INV", "posting_date": nowdate(), "company": company, "fiscal_year": webnotes.conn.get_default("fiscal_year"), "currency": "USD", "price_list_currency": "USD", "conversion_rate": 50.0, "plc_conversion_rate": 50.0, "grand_total_export": 0 }, # items { "doctype": "Sales Invoice Item", "warehouse": "Default Warehouse", "item_code": "Home Desktop 100", "qty": 10, "export_rate": 50, "adj_rate": 10, "parentfield": "sales_invoice_items", "uom": "Nos", "item_tax_rate": json.dumps({"Excise Duty - %s" % abbr: 10}) }, { "doctype": "Sales Invoice Item", "warehouse": "Default Warehouse", "item_code": "Home Desktop 200", "qty": 5, "export_rate": 150, "adj_rate": 20, "parentfield": "sales_invoice_items", "uom": "Nos" }, # taxes { "doctype": "Sales Taxes and Charges", "charge_type": "On Net Total", "account_head": "Excise Duty - %s" % abbr, "rate": 12, "parentfield": "other_charges", "included_in_print_rate": 1 }, { "doctype": "Sales Taxes and Charges", "charge_type": "On Previous Row Amount", "account_head": "Education Cess - %s" % abbr, "rate": 2, "row_id": 1, "parentfield": "other_charges", "included_in_print_rate": 1 }, { "doctype": "Sales Taxes and Charges", "charge_type": "On Previous Row Amount", "account_head": "S&H Education Cess - %s" % abbr, "rate": 1, "row_id": 1, "parentfield": "other_charges", "included_in_print_rate": 1 }, { "doctype": "Sales Taxes and Charges", "charge_type": "On Previous Row Total", "account_head": "CST - %s" % abbr, "rate": 2, "row_id": 3, "parentfield": "other_charges", "included_in_print_rate": 1, "cost_center_other_charges": "Default Cost Center - %s" % abbr }, { "doctype": "Sales Taxes and Charges", "charge_type": "On Net Total", "account_head": "VAT - Test - %s" % abbr, "rate": 12.5, "parentfield": "other_charges", "included_in_print_rate": 1 }, { "doctype": "Sales Taxes and Charges", "charge_type": "On Net Total", "account_head": "Customs Duty - %s" % abbr, "rate": 10, "parentfield": "other_charges", "cost_center_other_charges": "Default Cost Center - %s" % abbr }, { "doctype": "Sales Taxes and Charges", "charge_type": "Actual", "account_head": "Shipping Charges - %s" % abbr, "rate": 100, "parentfield": "other_charges", "cost_center_other_charges": "Default Cost Center - %s" % abbr }, { "doctype": "Sales Taxes and Charges", "charge_type": "On Previous Row Total", "account_head": "adj_rate - %s" % abbr, "rate": -10, "row_id": 7, "parentfield": "other_charges", "cost_center_other_charges": "Default Cost Center - %s" % abbr }, ] controller = webnotes.insert(DocList(doclist)) controller.load_from_db() from controllers.tax_controller import TaxController tax_controller = TaxController(controller.doc, controller.doclist) tax_controller.item_table_field = "entries" tax_controller.calculate_taxes_and_totals() controller.doc = tax_controller.doc controller.doclist = tax_controller.doclist controller.save() controller.load_from_db() dl = controller.doclist # test item values calculation expected_values = [ { "item_code": "Home Desktop 100", "ref_rate": 55.5556, "adj_rate": 10, "export_amount": 500, "base_ref_rate": 2222.1156, "basic_rate": 1999.904, "amount": 19999.04 }, { "item_code": "Home Desktop 200", "ref_rate": 187.5, "adj_rate": 20, "export_amount": 750, "base_ref_rate": 7375.664, "basic_rate": 5900.5312, "amount": 29502.66 }, ] for i, item in enumerate(dl.get({"parentfield": "sales_invoice_items"})): for key, val in expected_values[i].items(): self.assertEqual(item.fields.get(key), val) # test tax amounts and totals expected_values = [ ["Excise Duty - %s" % abbr, 5540.22, 55041.92, 0, 1250], ["Education Cess - %s" % abbr, 110.81, 55152.73, 0, 1250], ["S&H Education Cess - %s" % abbr, 55.4, 55208.13, 0, 1250], ["CST - %s" % abbr, 1104.16, 56312.29, 0, 1250], ["VAT - Test - %s" % abbr, 6187.71, 62500, 0, 1250], ["Customs Duty - %s" % abbr, 4950.17, 67450.17, 99.01, 1349.01], ["Shipping Charges - %s" % abbr, 5000, 72450.17, 100, 1449.01], ["adj_rate - %s" % abbr, -7245.01, 65205.16, -144.9, 1304.11], ] for i, tax in enumerate(dl.get({"parentfield": "other_charges"})): # print tax.account_head, tax.tax_amount, tax.total, tax.tax_amount_print, \ # tax.total_print 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]) # self.assertEqual(tax.tax_amount_print, expected_values[i][3]) self.assertEqual(tax.total_print, expected_values[i][4]) # test net total self.assertEqual(dl[0].net_total, 49501.7) self.assertEqual(dl[0].net_total_print, 1250) # # test grand total self.assertEqual(dl[0].grand_total, 65205.16) self.assertEqual(dl[0].grand_total_export, 1304.11)
def test_sales_invoice_with_inclusive_tax(self): doclist = [ # parent { "doctype": "Sales Invoice", "debit_to": "West Wind Inc. - %s" % abbr, "customer_name": "West Wind Inc.", "naming_series": "INV", "posting_date": nowdate(), "company": company, "fiscal_year": webnotes.conn.get_default("fiscal_year"), "currency": webnotes.conn.get_default("currency"), "price_list_currency": webnotes.conn.get_default("currency"), "conversion_rate": 1.0, "plc_conversion_rate": 1.0, "grand_total_export": 0 }, # items { "doctype": "Sales Invoice Item", "warehouse": "Default Warehouse", "item_code": "Home Desktop 100", "qty": 10, "export_rate": 62.503, "parentfield": "sales_invoice_items", "uom": "Nos", "item_tax_rate": json.dumps({"Excise Duty - %s" % abbr: 10}) }, { "doctype": "Sales Invoice Item", "warehouse": "Default Warehouse", "item_code": "Home Desktop 200", "qty": 5, "export_rate": 190.6608, "parentfield": "sales_invoice_items", "uom": "Nos" }, # taxes { "doctype": "Sales Taxes and Charges", "charge_type": "On Net Total", "account_head": "Excise Duty - %s" % abbr, "rate": 12, "parentfield": "other_charges", "included_in_print_rate": 1 }, { "doctype": "Sales Taxes and Charges", "charge_type": "On Previous Row Amount", "account_head": "Education Cess - %s" % abbr, "rate": 2, "row_id": 1, "parentfield": "other_charges", "included_in_print_rate": 1 }, { "doctype": "Sales Taxes and Charges", "charge_type": "On Previous Row Amount", "account_head": "S&H Education Cess - %s" % abbr, "rate": 1, "row_id": 1, "parentfield": "other_charges", "included_in_print_rate": 1 }, { "doctype": "Sales Taxes and Charges", "charge_type": "On Previous Row Total", "account_head": "CST - %s" % abbr, "rate": 2, "row_id": 3, "parentfield": "other_charges", "included_in_print_rate": 1, "cost_center_other_charges": "Default Cost Center - %s" % abbr }, { "doctype": "Sales Taxes and Charges", "charge_type": "On Net Total", "account_head": "VAT - Test - %s" % abbr, "rate": 12.5, "parentfield": "other_charges", "included_in_print_rate": 1 }, { "doctype": "Sales Taxes and Charges", "charge_type": "On Net Total", "account_head": "Customs Duty - %s" % abbr, "rate": 10, "parentfield": "other_charges", "cost_center_other_charges": "Default Cost Center - %s" % abbr }, { "doctype": "Sales Taxes and Charges", "charge_type": "Actual", "account_head": "Shipping Charges - %s" % abbr, "rate": 100, "parentfield": "other_charges", "cost_center_other_charges": "Default Cost Center - %s" % abbr }, { "doctype": "Sales Taxes and Charges", "charge_type": "On Previous Row Total", "account_head": "adj_rate - %s" % abbr, "rate": -10, "row_id": 7, "parentfield": "other_charges", "cost_center_other_charges": "Default Cost Center - %s" % abbr }, ] controller = webnotes.insert(DocList(doclist)) controller.load_from_db() from controllers.tax_controller import TaxController tax_controller = TaxController(controller.doc, controller.doclist) tax_controller.item_table_field = "entries" tax_controller.calculate_taxes_and_totals() controller.doc = tax_controller.doc controller.doclist = tax_controller.doclist controller.save() controller.load_from_db() dl = controller.doclist # test item values calculation expected_values = [ { "item_code": "Home Desktop 100", "ref_rate": 62.503, "adj_rate": 0, "export_amount": 625.03, "base_ref_rate": 50, "basic_rate": 50, "amount": 500 }, { "item_code": "Home Desktop 200", "ref_rate": 190.6608, "adj_rate": 0, "export_amount": 953.3, "base_ref_rate": 150, "basic_rate": 150, "amount": 750 }, ] for i, item in enumerate(dl.get({"parentfield": "sales_invoice_items"})): for key, val in expected_values[i].items(): self.assertEqual(item.fields.get(key), val) # test tax amounts and totals expected_values = [ ["Excise Duty - %s" % abbr, 140, 1390, 0, 1578.33], ["Education Cess - %s" % abbr, 2.8, 1392.8, 0, 1578.33], ["S&H Education Cess - %s" % abbr, 1.4, 1394.2, 0, 1578.33], ["CST - %s" % abbr, 27.88, 1422.08, 0, 1578.33], ["VAT - Test - %s" % abbr, 156.25, 1578.33, 0, 1578.33], ["Customs Duty - %s" % abbr, 125, 1703.33, 125, 1703.33], ["Shipping Charges - %s" % abbr, 100, 1803.33, 100, 1803.33], ["adj_rate - %s" % abbr, -180.33, 1623, -180.33, 1623], ] for i, tax in enumerate(dl.get({"parentfield": "other_charges"})): # print tax.account_head, tax.tax_amount, tax.total, tax.tax_amount_print, \ # tax.total_print 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]) # self.assertEqual(tax.tax_amount_print, expected_values[i][3]) self.assertEqual(tax.total_print, expected_values[i][4]) # test net total self.assertEqual(dl[0].net_total, 1250) self.assertEqual(dl[0].net_total_print, 1578.33) # # test grand total self.assertEqual(dl[0].grand_total, 1623) self.assertEqual(dl[0].grand_total_export, 1623)
def execute(): import webnotes from webnotes.model.doclist import DocList DocList("Website Settings", "Website Settings").save()
def test_sales_invoice(self): from webnotes.model.doclist import DocList doclist = [] + [d.copy() for d in sales_invoice_doclist] controller = webnotes.insert(DocList(doclist)) controller.load_from_db() from controllers.tax_controller import TaxController tax_controller = TaxController(controller.doc, controller.doclist) tax_controller.item_table_field = "entries" tax_controller.calculate_taxes_and_totals() controller.doc = tax_controller.doc controller.doclist = tax_controller.doclist controller.save() controller.load_from_db() dl = controller.doclist # test net total self.assertEqual(dl[0].net_total, 1250) # test item values calculation expected_values = [ { "item_code": "Home Desktop 100", "ref_rate": 50, "adj_rate": 0, "export_amount": 500, "base_ref_rate": 50, "basic_rate": 50, "amount": 500 }, { "item_code": "Home Desktop 200", "ref_rate": 150, "adj_rate": 0, "export_amount": 750, "base_ref_rate": 150, "basic_rate": 150, "amount": 750 }, ] for i, item in enumerate(dl.get({"parentfield": "sales_invoice_items"})): for key, val in expected_values[i].items(): self.assertEqual(item.fields.get(key), val) # test tax amounts and totals expected_values = [ ["Shipping Charges - %s" % abbr, 100, 1350], ["Customs Duty - %s" % abbr, 125, 1475], ["Excise Duty - %s" % abbr, 140, 1615], ["Education Cess - %s" % abbr, 2.8, 1617.8], ["S&H Education Cess - %s" % abbr, 1.4, 1619.2], ["CST - %s" % abbr, 32.38, 1651.58], ["VAT - Test - %s" % abbr, 156.25, 1807.83], ["adj_rate - %s" % abbr, -180.78, 1627.05], ] for i, tax in enumerate(dl.get({"parentfield": "other_charges"})): # print tax.account_head, tax.tax_amount, tax.total 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])
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 = []
def doclist(lst=None): from webnotes.model.doclist import DocList return DocList(lst)