Test Cases - Journal Voucher, Purchase Invoice, Period Closing Voucher frappe/frappe#478

This commit is contained in:
Anand Doshi 2014-04-08 13:53:35 +05:30
parent 2ce39cf770
commit cd71e1d8ab
8 changed files with 263 additions and 259 deletions

View File

@ -9,47 +9,51 @@ import frappe
class TestJournalVoucher(unittest.TestCase): class TestJournalVoucher(unittest.TestCase):
def test_journal_voucher_with_against_jv(self): def test_journal_voucher_with_against_jv(self):
self.clear_account_balance() self.clear_account_balance()
jv_invoice = frappe.copy_doc(test_records[1]) jv_invoice = frappe.copy_doc(test_records[2])
jv_invoice.insert() jv_invoice.insert()
jv_invoice.submit() jv_invoice.submit()
self.assertTrue(frappe.db.sql("""select name from `tabJournal Voucher Detail`
where account = %s and docstatus = 1 and parent = %s""",
("_Test Customer - _TC", jv_invoice.name)))
self.assertTrue(not frappe.db.sql("""select name from `tabJournal Voucher Detail` self.assertTrue(not frappe.db.sql("""select name from `tabJournal Voucher Detail`
where against_jv=%s""", jv_invoice.name)) where against_jv=%s""", jv_invoice.name))
jv_payment = frappe.copy_doc(test_records[0]) jv_payment = frappe.copy_doc(test_records[0])
jv_payment.get("entries")[0].against_jv = jv_invoice.name jv_payment.get("entries")[0].against_jv = jv_invoice.name
jv_payment.insert() jv_payment.insert()
jv_payment.submit() jv_payment.submit()
self.assertTrue(frappe.db.sql("""select name from `tabJournal Voucher Detail` self.assertTrue(frappe.db.sql("""select name from `tabJournal Voucher Detail`
where against_jv=%s""", jv_invoice.name)) where against_jv=%s""", jv_invoice.name))
self.assertTrue(frappe.db.sql("""select name from `tabJournal Voucher Detail` self.assertTrue(frappe.db.sql("""select name from `tabJournal Voucher Detail`
where against_jv=%s and credit=400""", jv_invoice.name)) where against_jv=%s and credit=400""", jv_invoice.name))
# cancel jv_invoice # cancel jv_invoice
jv_invoice.cancel() jv_invoice.cancel()
self.assertTrue(not frappe.db.sql("""select name from `tabJournal Voucher Detail` self.assertTrue(not frappe.db.sql("""select name from `tabJournal Voucher Detail`
where against_jv=%s""", jv_invoice.name)) where against_jv=%s""", jv_invoice.name))
def test_jv_against_stock_account(self): def test_jv_against_stock_account(self):
from erpnext.stock.doctype.purchase_receipt.test_purchase_receipt import set_perpetual_inventory from erpnext.stock.doctype.purchase_receipt.test_purchase_receipt import set_perpetual_inventory
set_perpetual_inventory() set_perpetual_inventory()
jv = frappe.copy_doc(test_records[0]) jv = frappe.copy_doc(test_records[0])
jv.get("entries")[0].account = "_Test Warehouse - _TC" jv.get("entries")[0].account = "_Test Warehouse - _TC"
jv.insert() jv.insert()
from erpnext.accounts.general_ledger import StockAccountInvalidTransaction from erpnext.accounts.general_ledger import StockAccountInvalidTransaction
self.assertRaises(StockAccountInvalidTransaction, jv.submit) self.assertRaises(StockAccountInvalidTransaction, jv.submit)
set_perpetual_inventory(0) set_perpetual_inventory(0)
def test_monthly_budget_crossed_ignore(self): def test_monthly_budget_crossed_ignore(self):
frappe.db.set_value("Company", "_Test Company", "monthly_bgt_flag", "Ignore") frappe.db.set_value("Company", "_Test Company", "monthly_bgt_flag", "Ignore")
self.clear_account_balance() self.clear_account_balance()
jv = frappe.copy_doc(test_records[0]) jv = frappe.copy_doc(test_records[0])
jv.get("entries")[1].account = "_Test Account Cost for Goods Sold - _TC" jv.get("entries")[1].account = "_Test Account Cost for Goods Sold - _TC"
jv.get("entries")[1].cost_center = "_Test Cost Center - _TC" jv.get("entries")[1].cost_center = "_Test Cost Center - _TC"
@ -57,32 +61,32 @@ class TestJournalVoucher(unittest.TestCase):
jv.get("entries")[0].credit = 20000.0 jv.get("entries")[0].credit = 20000.0
jv.insert() jv.insert()
jv.submit() jv.submit()
self.assertTrue(frappe.db.get_value("GL Entry", self.assertTrue(frappe.db.get_value("GL Entry",
{"voucher_type": "Journal Voucher", "voucher_no": jv.name})) {"voucher_type": "Journal Voucher", "voucher_no": jv.name}))
def test_monthly_budget_crossed_stop(self): def test_monthly_budget_crossed_stop(self):
from erpnext.accounts.utils import BudgetError from erpnext.accounts.utils import BudgetError
frappe.db.set_value("Company", "_Test Company", "monthly_bgt_flag", "Stop") frappe.db.set_value("Company", "_Test Company", "monthly_bgt_flag", "Stop")
self.clear_account_balance() self.clear_account_balance()
jv = frappe.copy_doc(test_records[0]) jv = frappe.copy_doc(test_records[0])
jv.get("entries")[1].account = "_Test Account Cost for Goods Sold - _TC" jv.get("entries")[1].account = "_Test Account Cost for Goods Sold - _TC"
jv.get("entries")[1].cost_center = "_Test Cost Center - _TC" jv.get("entries")[1].cost_center = "_Test Cost Center - _TC"
jv.get("entries")[1].debit = 20000.0 jv.get("entries")[1].debit = 20000.0
jv.get("entries")[0].credit = 20000.0 jv.get("entries")[0].credit = 20000.0
jv.insert() jv.insert()
self.assertRaises(BudgetError, jv.submit) self.assertRaises(BudgetError, jv.submit)
frappe.db.set_value("Company", "_Test Company", "monthly_bgt_flag", "Ignore") frappe.db.set_value("Company", "_Test Company", "monthly_bgt_flag", "Ignore")
def test_yearly_budget_crossed_stop(self): def test_yearly_budget_crossed_stop(self):
from erpnext.accounts.utils import BudgetError from erpnext.accounts.utils import BudgetError
self.clear_account_balance() self.clear_account_balance()
self.test_monthly_budget_crossed_ignore() self.test_monthly_budget_crossed_ignore()
frappe.db.set_value("Company", "_Test Company", "yearly_bgt_flag", "Stop") frappe.db.set_value("Company", "_Test Company", "yearly_bgt_flag", "Stop")
jv = frappe.copy_doc(test_records[0]) jv = frappe.copy_doc(test_records[0])
jv.posting_date = "2013-08-12" jv.posting_date = "2013-08-12"
jv.get("entries")[1].account = "_Test Account Cost for Goods Sold - _TC" jv.get("entries")[1].account = "_Test Account Cost for Goods Sold - _TC"
@ -90,42 +94,42 @@ class TestJournalVoucher(unittest.TestCase):
jv.get("entries")[1].debit = 150000.0 jv.get("entries")[1].debit = 150000.0
jv.get("entries")[0].credit = 150000.0 jv.get("entries")[0].credit = 150000.0
jv.insert() jv.insert()
self.assertRaises(BudgetError, jv.submit) self.assertRaises(BudgetError, jv.submit)
frappe.db.set_value("Company", "_Test Company", "yearly_bgt_flag", "Ignore") frappe.db.set_value("Company", "_Test Company", "yearly_bgt_flag", "Ignore")
def test_monthly_budget_on_cancellation(self): def test_monthly_budget_on_cancellation(self):
from erpnext.accounts.utils import BudgetError from erpnext.accounts.utils import BudgetError
frappe.db.set_value("Company", "_Test Company", "monthly_bgt_flag", "Stop") frappe.db.set_value("Company", "_Test Company", "monthly_bgt_flag", "Stop")
self.clear_account_balance() self.clear_account_balance()
jv = frappe.copy_doc(test_records[0]) jv = frappe.copy_doc(test_records[0])
jv.get("entries")[0].account = "_Test Account Cost for Goods Sold - _TC" jv.get("entries")[0].account = "_Test Account Cost for Goods Sold - _TC"
jv.get("entries")[0].cost_center = "_Test Cost Center - _TC" jv.get("entries")[0].cost_center = "_Test Cost Center - _TC"
jv.get("entries")[0].credit = 30000.0 jv.get("entries")[0].credit = 30000.0
jv.get("entries")[1].debit = 30000.0 jv.get("entries")[1].debit = 30000.0
jv.submit() jv.submit()
self.assertTrue(frappe.db.get_value("GL Entry", self.assertTrue(frappe.db.get_value("GL Entry",
{"voucher_type": "Journal Voucher", "voucher_no": jv.name})) {"voucher_type": "Journal Voucher", "voucher_no": jv.name}))
jv1 = frappe.copy_doc(test_records[0]) jv1 = frappe.copy_doc(test_records[0])
jv1.get("entries")[1].account = "_Test Account Cost for Goods Sold - _TC" jv1.get("entries")[1].account = "_Test Account Cost for Goods Sold - _TC"
jv1.get("entries")[1].cost_center = "_Test Cost Center - _TC" jv1.get("entries")[1].cost_center = "_Test Cost Center - _TC"
jv1.get("entries")[1].debit = 40000.0 jv1.get("entries")[1].debit = 40000.0
jv1.get("entries")[0].credit = 40000.0 jv1.get("entries")[0].credit = 40000.0
jv1.submit() jv1.submit()
self.assertTrue(frappe.db.get_value("GL Entry", self.assertTrue(frappe.db.get_value("GL Entry",
{"voucher_type": "Journal Voucher", "voucher_no": jv1.name})) {"voucher_type": "Journal Voucher", "voucher_no": jv1.name}))
self.assertRaises(BudgetError, jv.cancel) self.assertRaises(BudgetError, jv.cancel)
frappe.db.set_value("Company", "_Test Company", "monthly_bgt_flag", "Ignore") frappe.db.set_value("Company", "_Test Company", "monthly_bgt_flag", "Ignore")
def clear_account_balance(self): def clear_account_balance(self):
frappe.db.sql("""delete from `tabGL Entry`""") frappe.db.sql("""delete from `tabGL Entry`""")
test_records = frappe.get_test_records('Journal Voucher')
test_records = frappe.get_test_records('Journal Voucher')

View File

@ -1,84 +1,84 @@
[ [
{ {
"cheque_date": "2013-02-14", "cheque_date": "2013-02-14",
"cheque_no": "33", "cheque_no": "33",
"company": "_Test Company", "company": "_Test Company",
"doctype": "Journal Voucher", "doctype": "Journal Voucher",
"entries": [ "entries": [
{ {
"account": "_Test Customer - _TC", "account": "_Test Customer - _TC",
"credit": 400.0, "credit": 400.0,
"debit": 0.0, "debit": 0.0,
"doctype": "Journal Voucher Detail", "doctype": "Journal Voucher Detail",
"parentfield": "entries" "parentfield": "entries"
}, },
{ {
"account": "_Test Account Bank Account - _TC", "account": "_Test Account Bank Account - _TC",
"credit": 0.0, "credit": 0.0,
"debit": 400.0, "debit": 400.0,
"doctype": "Journal Voucher Detail", "doctype": "Journal Voucher Detail",
"parentfield": "entries" "parentfield": "entries"
} }
], ],
"fiscal_year": "_Test Fiscal Year 2013", "fiscal_year": "_Test Fiscal Year 2013",
"naming_series": "_T-Journal Voucher-", "naming_series": "_T-Journal Voucher-",
"posting_date": "2013-02-14", "posting_date": "2013-02-14",
"user_remark": "test", "user_remark": "test",
"voucher_type": "Bank Voucher" "voucher_type": "Bank Voucher"
}, },
{ {
"cheque_date": "2013-02-14", "cheque_date": "2013-02-14",
"cheque_no": "33", "cheque_no": "33",
"company": "_Test Company", "company": "_Test Company",
"doctype": "Journal Voucher", "doctype": "Journal Voucher",
"entries": [ "entries": [
{ {
"account": "_Test Supplier - _TC", "account": "_Test Supplier - _TC",
"credit": 0.0, "credit": 0.0,
"debit": 400.0, "debit": 400.0,
"doctype": "Journal Voucher Detail", "doctype": "Journal Voucher Detail",
"parentfield": "entries" "parentfield": "entries"
}, },
{ {
"account": "_Test Account Bank Account - _TC", "account": "_Test Account Bank Account - _TC",
"credit": 400.0, "credit": 400.0,
"debit": 0.0, "debit": 0.0,
"doctype": "Journal Voucher Detail", "doctype": "Journal Voucher Detail",
"parentfield": "entries" "parentfield": "entries"
} }
], ],
"fiscal_year": "_Test Fiscal Year 2013", "fiscal_year": "_Test Fiscal Year 2013",
"naming_series": "_T-Journal Voucher-", "naming_series": "_T-Journal Voucher-",
"posting_date": "2013-02-14", "posting_date": "2013-02-14",
"user_remark": "test", "user_remark": "test",
"voucher_type": "Bank Voucher" "voucher_type": "Bank Voucher"
}, },
{ {
"cheque_date": "2013-02-14", "cheque_date": "2013-02-14",
"cheque_no": "33", "cheque_no": "33",
"company": "_Test Company", "company": "_Test Company",
"doctype": "Journal Voucher", "doctype": "Journal Voucher",
"entries": [ "entries": [
{ {
"account": "_Test Customer - _TC", "account": "_Test Customer - _TC",
"credit": 0.0, "credit": 0.0,
"debit": 400.0, "debit": 400.0,
"doctype": "Journal Voucher Detail", "doctype": "Journal Voucher Detail",
"parentfield": "entries" "parentfield": "entries"
}, },
{ {
"account": "Sales - _TC", "account": "Sales - _TC",
"cost_center": "_Test Cost Center - _TC", "cost_center": "_Test Cost Center - _TC",
"credit": 400.0, "credit": 400.0,
"debit": 0.0, "debit": 0.0,
"doctype": "Journal Voucher Detail", "doctype": "Journal Voucher Detail",
"parentfield": "entries" "parentfield": "entries"
} }
], ],
"fiscal_year": "_Test Fiscal Year 2013", "fiscal_year": "_Test Fiscal Year 2013",
"naming_series": "_T-Journal Voucher-", "naming_series": "_T-Journal Voucher-",
"posting_date": "2013-02-14", "posting_date": "2013-02-14",
"user_remark": "test", "user_remark": "test",
"voucher_type": "Bank Voucher" "voucher_type": "Bank Voucher"
} }
] ]

View File

@ -5,34 +5,34 @@
from __future__ import unicode_literals from __future__ import unicode_literals
import unittest import unittest
import frappe import frappe
from erpnext.accounts.doctype.journal_voucher.test_journal_voucher import test_records as jv_records
class TestPeriodClosingVoucher(unittest.TestCase): class TestPeriodClosingVoucher(unittest.TestCase):
def test_closing_entry(self): def test_closing_entry(self):
# clear GL Entries # clear GL Entries
frappe.db.sql("""delete from `tabGL Entry`""") frappe.db.sql("""delete from `tabGL Entry`""")
from erpnext.accounts.doctype.journal_voucher.test_journal_voucher import test_records as jv_records
jv = frappe.copy_doc(jv_records[2]) jv = frappe.copy_doc(jv_records[2])
jv.insert() jv.insert()
jv.submit() jv.submit()
jv1 = frappe.copy_doc(jv_records[0]) jv1 = frappe.copy_doc(jv_records[0])
jv1.get("entries")[1].account = "_Test Account Cost for Goods Sold - _TC" jv1.get("entries")[1].account = "_Test Account Cost for Goods Sold - _TC"
jv1.get("entries")[1].cost_center = "_Test Cost Center - _TC"
jv1.get("entries")[1].debit = 600.0 jv1.get("entries")[1].debit = 600.0
jv1.get("entries")[0].credit = 600.0 jv1.get("entries")[0].credit = 600.0
jv1.insert() jv1.insert()
jv1.submit() jv1.submit()
pcv = frappe.copy_doc(test_record) pcv = frappe.copy_doc(test_records[0])
pcv.insert() pcv.insert()
pcv.submit() pcv.submit()
gl_entries = frappe.db.sql("""select account, debit, credit gl_entries = frappe.db.sql("""select account, debit, credit
from `tabGL Entry` where voucher_type='Period Closing Voucher' and voucher_no=%s from `tabGL Entry` where voucher_type='Period Closing Voucher' and voucher_no=%s
order by account asc, debit asc""", pcv.name, as_dict=1) order by account asc, debit asc""", pcv.name, as_dict=1)
self.assertTrue(gl_entries) self.assertTrue(gl_entries)
expected_gl_entries = sorted([ expected_gl_entries = sorted([
["_Test Account Reserves and Surplus - _TC", 200.0, 0.0], ["_Test Account Reserves and Surplus - _TC", 200.0, 0.0],
["_Test Account Cost for Goods Sold - _TC", 0.0, 600.0], ["_Test Account Cost for Goods Sold - _TC", 0.0, 600.0],
@ -42,15 +42,7 @@ class TestPeriodClosingVoucher(unittest.TestCase):
self.assertEquals(expected_gl_entries[i][0], gle.account) self.assertEquals(expected_gl_entries[i][0], gle.account)
self.assertEquals(expected_gl_entries[i][1], gle.debit) self.assertEquals(expected_gl_entries[i][1], gle.debit)
self.assertEquals(expected_gl_entries[i][2], gle.credit) self.assertEquals(expected_gl_entries[i][2], gle.credit)
test_dependencies = ["Customer", "Cost Center"] test_dependencies = ["Customer", "Cost Center"]
test_records = frappe.get_test_records("Period Closing Voucher")
test_record = [{
"doctype": "Period Closing Voucher",
"closing_account_head": "_Test Account Reserves and Surplus - _TC",
"company": "_Test Company",
"fiscal_year": "_Test Fiscal Year 2013",
"posting_date": "2013-03-31",
"remarks": "test"
}]

View File

@ -0,0 +1,8 @@
[{
"doctype": "Period Closing Voucher",
"closing_account_head": "_Test Account Reserves and Surplus - _TC",
"company": "_Test Company",
"fiscal_year": "_Test Fiscal Year 2013",
"posting_date": "2013-03-31",
"remarks": "test"
}]

View File

@ -11,16 +11,16 @@ class TestPricingRule(unittest.TestCase):
from erpnext.stock.get_item_details import get_item_details from erpnext.stock.get_item_details import get_item_details
from frappe import MandatoryError from frappe import MandatoryError
test_record = [{ test_record = {
"doctype": "Pricing Rule", "doctype": "Pricing Rule",
"apply_on": "Item Code", "apply_on": "Item Code",
"item_code": "_Test Item", "item_code": "_Test Item",
"price_or_discount": "Discount Percentage", "price_or_discount": "Discount Percentage",
"price": 0, "price": 0,
"discount_percentage": 10, "discount_percentage": 10,
}] }
frappe.copy_doc(test_record).insert() frappe.get_doc(test_record.copy()).insert()
args = frappe._dict({ args = frappe._dict({
"item_code": "_Test Item", "item_code": "_Test Item",
"company": "_Test Company", "company": "_Test Company",
@ -34,11 +34,11 @@ class TestPricingRule(unittest.TestCase):
"transaction_type": "selling", "transaction_type": "selling",
"customer": "_Test Customer", "customer": "_Test Customer",
}) })
details = get_item_details(args) details = get_item_details(args)
self.assertEquals(details.get("discount_percentage"), 10) self.assertEquals(details.get("discount_percentage"), 10)
prule = frappe.copy_doc(test_record) prule = frappe.get_doc(test_record.copy())
prule.applicable_for = "Customer" prule.applicable_for = "Customer"
self.assertRaises(MandatoryError, prule.insert) self.assertRaises(MandatoryError, prule.insert)
prule.customer = "_Test Customer" prule.customer = "_Test Customer"
@ -46,34 +46,34 @@ class TestPricingRule(unittest.TestCase):
prule.insert() prule.insert()
details = get_item_details(args) details = get_item_details(args)
self.assertEquals(details.get("discount_percentage"), 20) self.assertEquals(details.get("discount_percentage"), 20)
prule = frappe.copy_doc(test_record) prule = frappe.get_doc(test_record.copy())
prule.apply_on = "Item Group" prule.apply_on = "Item Group"
prule.item_group = "All Item Groups" prule.item_group = "All Item Groups"
prule.discount_percentage = 15 prule.discount_percentage = 15
prule.insert() prule.insert()
args.customer = None args.customer = None
details = get_item_details(args) details = get_item_details(args)
self.assertEquals(details.get("discount_percentage"), 10) self.assertEquals(details.get("discount_percentage"), 10)
prule = frappe.copy_doc(test_record) prule = frappe.get_doc(test_record.copy())
prule.applicable_for = "Campaign" prule.applicable_for = "Campaign"
prule.campaign = "_Test Campaign" prule.campaign = "_Test Campaign"
prule.discount_percentage = 5 prule.discount_percentage = 5
prule.priority = 8 prule.priority = 8
prule.insert() prule.insert()
args.campaign = "_Test Campaign" args.campaign = "_Test Campaign"
details = get_item_details(args) details = get_item_details(args)
self.assertEquals(details.get("discount_percentage"), 5) self.assertEquals(details.get("discount_percentage"), 5)
frappe.db.sql("update `tabPricing Rule` set priority=NULL where campaign='_Test Campaign'") frappe.db.sql("update `tabPricing Rule` set priority=NULL where campaign='_Test Campaign'")
details = get_item_details(args) details = get_item_details(args)
self.assertEquals(details.get("discount_percentage"), 15) self.assertEquals(details.get("discount_percentage"), 15)
args.item_code = "_Test Item 2" args.item_code = "_Test Item 2"
details = get_item_details(args) details = get_item_details(args)
self.assertEquals(details.get("discount_percentage"), 15) self.assertEquals(details.get("discount_percentage"), 15)
frappe.db.sql("delete from `tabPricing Rule`") frappe.db.sql("delete from `tabPricing Rule`")

View File

@ -6,7 +6,7 @@ from __future__ import unicode_literals
import unittest import unittest
import frappe import frappe
import frappe.model import frappe.model
import json import json
from frappe.utils import cint from frappe.utils import cint
import frappe.defaults import frappe.defaults
from erpnext.stock.doctype.purchase_receipt.test_purchase_receipt import set_perpetual_inventory from erpnext.stock.doctype.purchase_receipt.test_purchase_receipt import set_perpetual_inventory
@ -18,13 +18,13 @@ class TestPurchaseInvoice(unittest.TestCase):
def test_gl_entries_without_auto_accounting_for_stock(self): def test_gl_entries_without_auto_accounting_for_stock(self):
set_perpetual_inventory(0) set_perpetual_inventory(0)
self.assertTrue(not cint(frappe.defaults.get_global_default("auto_accounting_for_stock"))) self.assertTrue(not cint(frappe.defaults.get_global_default("auto_accounting_for_stock")))
wrapper = frappe.copy_doc(test_records[0]) wrapper = frappe.copy_doc(test_records[0])
wrapper.insert() wrapper.insert()
wrapper.submit() wrapper.submit()
wrapper.load_from_db() wrapper.load_from_db()
dl = wrapper dl = wrapper
expected_gl_entries = { expected_gl_entries = {
"_Test Supplier - _TC": [0, 1512.30], "_Test Supplier - _TC": [0, 1512.30],
"_Test Account Cost for Goods Sold - _TC": [1250, 0], "_Test Account Cost for Goods Sold - _TC": [1250, 0],
@ -40,20 +40,20 @@ class TestPurchaseInvoice(unittest.TestCase):
where voucher_type = 'Purchase Invoice' and voucher_no = %s""", dl.name, as_dict=1) where voucher_type = 'Purchase Invoice' and voucher_no = %s""", dl.name, as_dict=1)
for d in gl_entries: for d in gl_entries:
self.assertEqual([d.debit, d.credit], expected_gl_entries.get(d.account)) self.assertEqual([d.debit, d.credit], expected_gl_entries.get(d.account))
def test_gl_entries_with_auto_accounting_for_stock(self): def test_gl_entries_with_auto_accounting_for_stock(self):
set_perpetual_inventory(1) set_perpetual_inventory(1)
self.assertEqual(cint(frappe.defaults.get_global_default("auto_accounting_for_stock")), 1) self.assertEqual(cint(frappe.defaults.get_global_default("auto_accounting_for_stock")), 1)
pi = frappe.copy_doc(test_records[1]) pi = frappe.copy_doc(test_records[1])
pi.insert() pi.insert()
pi.submit() pi.submit()
gl_entries = frappe.db.sql("""select account, debit, credit gl_entries = frappe.db.sql("""select account, debit, credit
from `tabGL Entry` where voucher_type='Purchase Invoice' and voucher_no=%s from `tabGL Entry` where voucher_type='Purchase Invoice' and voucher_no=%s
order by account asc""", pi.name, as_dict=1) order by account asc""", pi.name, as_dict=1)
self.assertTrue(gl_entries) self.assertTrue(gl_entries)
expected_values = sorted([ expected_values = sorted([
["_Test Supplier - _TC", 0, 720], ["_Test Supplier - _TC", 0, 720],
["Stock Received But Not Billed - _TC", 750.0, 0], ["Stock Received But Not Billed - _TC", 750.0, 0],
@ -61,48 +61,48 @@ class TestPurchaseInvoice(unittest.TestCase):
["_Test Account VAT - _TC", 120.0, 0], ["_Test Account VAT - _TC", 120.0, 0],
["Expenses Included In Valuation - _TC", 0, 250.0], ["Expenses Included In Valuation - _TC", 0, 250.0],
]) ])
for i, gle in enumerate(gl_entries): for i, gle in enumerate(gl_entries):
self.assertEquals(expected_values[i][0], gle.account) self.assertEquals(expected_values[i][0], gle.account)
self.assertEquals(expected_values[i][1], gle.debit) self.assertEquals(expected_values[i][1], gle.debit)
self.assertEquals(expected_values[i][2], gle.credit) self.assertEquals(expected_values[i][2], gle.credit)
set_perpetual_inventory(0) set_perpetual_inventory(0)
def test_gl_entries_with_aia_for_non_stock_items(self): def test_gl_entries_with_aia_for_non_stock_items(self):
set_perpetual_inventory() set_perpetual_inventory()
self.assertEqual(cint(frappe.defaults.get_global_default("auto_accounting_for_stock")), 1) self.assertEqual(cint(frappe.defaults.get_global_default("auto_accounting_for_stock")), 1)
pi = frappe.copy_doc(test_records[1]) pi = frappe.copy_doc(test_records[1])
pi.get("entries")[0].item_code = "_Test Non Stock Item" pi.get("entries")[0].item_code = "_Test Non Stock Item"
pi.get("entries")[0].expense_account = "_Test Account Cost for Goods Sold - _TC" pi.get("entries")[0].expense_account = "_Test Account Cost for Goods Sold - _TC"
pi.get("entries").pop(2) pi.get("other_charges").pop(0)
pi.get("entries").pop(1) pi.get("other_charges").pop(1)
pi.insert() pi.insert()
pi.submit() pi.submit()
gl_entries = frappe.db.sql("""select account, debit, credit gl_entries = frappe.db.sql("""select account, debit, credit
from `tabGL Entry` where voucher_type='Purchase Invoice' and voucher_no=%s from `tabGL Entry` where voucher_type='Purchase Invoice' and voucher_no=%s
order by account asc""", pi.name, as_dict=1) order by account asc""", pi.name, as_dict=1)
self.assertTrue(gl_entries) self.assertTrue(gl_entries)
expected_values = sorted([ expected_values = sorted([
["_Test Supplier - _TC", 0, 620], ["_Test Supplier - _TC", 0, 620],
["_Test Account Cost for Goods Sold - _TC", 500.0, 0], ["_Test Account Cost for Goods Sold - _TC", 500.0, 0],
["_Test Account VAT - _TC", 120.0, 0], ["_Test Account VAT - _TC", 120.0, 0],
]) ])
for i, gle in enumerate(gl_entries): for i, gle in enumerate(gl_entries):
self.assertEquals(expected_values[i][0], gle.account) self.assertEquals(expected_values[i][0], gle.account)
self.assertEquals(expected_values[i][1], gle.debit) self.assertEquals(expected_values[i][1], gle.debit)
self.assertEquals(expected_values[i][2], gle.credit) self.assertEquals(expected_values[i][2], gle.credit)
set_perpetual_inventory(0) set_perpetual_inventory(0)
def test_purchase_invoice_calculation(self): def test_purchase_invoice_calculation(self):
wrapper = frappe.copy_doc(test_records[0]) wrapper = frappe.copy_doc(test_records[0])
wrapper.insert() wrapper.insert()
wrapper.load_from_db() wrapper.load_from_db()
expected_values = [ expected_values = [
["_Test Item Home Desktop 100", 90, 59], ["_Test Item Home Desktop 100", 90, 59],
["_Test Item Home Desktop 200", 135, 177] ["_Test Item Home Desktop 200", 135, 177]
@ -111,9 +111,9 @@ class TestPurchaseInvoice(unittest.TestCase):
self.assertEqual(item.item_code, expected_values[i][0]) self.assertEqual(item.item_code, expected_values[i][0])
self.assertEqual(item.item_tax_amount, expected_values[i][1]) self.assertEqual(item.item_tax_amount, expected_values[i][1])
self.assertEqual(item.valuation_rate, expected_values[i][2]) self.assertEqual(item.valuation_rate, expected_values[i][2])
self.assertEqual(wrapper.net_total, 1250) self.assertEqual(wrapper.net_total, 1250)
# tax amounts # tax amounts
expected_values = [ expected_values = [
["_Test Account Shipping Charges - _TC", 100, 1350], ["_Test Account Shipping Charges - _TC", 100, 1350],
@ -125,18 +125,18 @@ class TestPurchaseInvoice(unittest.TestCase):
["_Test Account VAT - _TC", 156.25, 1680.33], ["_Test Account VAT - _TC", 156.25, 1680.33],
["_Test Account Discount - _TC", 168.03, 1512.30], ["_Test Account Discount - _TC", 168.03, 1512.30],
] ]
for i, tax in enumerate(wrapper.get("other_charges")): for i, tax in enumerate(wrapper.get("other_charges")):
self.assertEqual(tax.account_head, expected_values[i][0]) self.assertEqual(tax.account_head, expected_values[i][0])
self.assertEqual(tax.tax_amount, expected_values[i][1]) self.assertEqual(tax.tax_amount, expected_values[i][1])
self.assertEqual(tax.total, expected_values[i][2]) self.assertEqual(tax.total, expected_values[i][2])
def test_purchase_invoice_with_subcontracted_item(self): def test_purchase_invoice_with_subcontracted_item(self):
wrapper = frappe.copy_doc(test_records[0]) wrapper = frappe.copy_doc(test_records[0])
wrapper.get("entries")[0].item_code = "_Test FG Item" wrapper.get("entries")[0].item_code = "_Test FG Item"
wrapper.insert() wrapper.insert()
wrapper.load_from_db() wrapper.load_from_db()
expected_values = [ expected_values = [
["_Test FG Item", 90, 7059], ["_Test FG Item", 90, 7059],
["_Test Item Home Desktop 200", 135, 177] ["_Test Item Home Desktop 200", 135, 177]
@ -145,7 +145,7 @@ class TestPurchaseInvoice(unittest.TestCase):
self.assertEqual(item.item_code, expected_values[i][0]) self.assertEqual(item.item_code, expected_values[i][0])
self.assertEqual(item.item_tax_amount, expected_values[i][1]) self.assertEqual(item.item_tax_amount, expected_values[i][1])
self.assertEqual(item.valuation_rate, expected_values[i][2]) self.assertEqual(item.valuation_rate, expected_values[i][2])
self.assertEqual(wrapper.net_total, 1250) self.assertEqual(wrapper.net_total, 1250)
# tax amounts # tax amounts
@ -164,15 +164,15 @@ class TestPurchaseInvoice(unittest.TestCase):
self.assertEqual(tax.account_head, expected_values[i][0]) self.assertEqual(tax.account_head, expected_values[i][0])
self.assertEqual(tax.tax_amount, expected_values[i][1]) self.assertEqual(tax.tax_amount, expected_values[i][1])
self.assertEqual(tax.total, expected_values[i][2]) self.assertEqual(tax.total, expected_values[i][2])
def test_purchase_invoice_with_advance(self): def test_purchase_invoice_with_advance(self):
from erpnext.accounts.doctype.journal_voucher.test_journal_voucher \ from erpnext.accounts.doctype.journal_voucher.test_journal_voucher \
import test_records as jv_test_records import test_records as jv_test_records
jv = frappe.copy_doc(jv_test_records[1]) jv = frappe.copy_doc(jv_test_records[1])
jv.insert() jv.insert()
jv.submit() jv.submit()
pi = frappe.copy_doc(test_records[0]) pi = frappe.copy_doc(test_records[0])
pi.append("advance_allocation_details", { pi.append("advance_allocation_details", {
"journal_voucher": jv.name, "journal_voucher": jv.name,
@ -184,18 +184,18 @@ class TestPurchaseInvoice(unittest.TestCase):
pi.insert() pi.insert()
pi.submit() pi.submit()
pi.load_from_db() pi.load_from_db()
self.assertTrue(frappe.db.sql("""select name from `tabJournal Voucher Detail` self.assertTrue(frappe.db.sql("""select name from `tabJournal Voucher Detail`
where against_voucher=%s""", pi.name)) where against_voucher=%s""", pi.name))
self.assertTrue(frappe.db.sql("""select name from `tabJournal Voucher Detail` self.assertTrue(frappe.db.sql("""select name from `tabJournal Voucher Detail`
where against_voucher=%s and debit=300""", pi.name)) where against_voucher=%s and debit=300""", pi.name))
self.assertEqual(pi.outstanding_amount, 1212.30) self.assertEqual(pi.outstanding_amount, 1212.30)
pi.cancel() pi.cancel()
self.assertTrue(not frappe.db.sql("""select name from `tabJournal Voucher Detail` self.assertTrue(not frappe.db.sql("""select name from `tabJournal Voucher Detail`
where against_voucher=%s""", pi.name)) where against_voucher=%s""", pi.name))
test_records = frappe.get_test_records('Purchase Invoice') test_records = frappe.get_test_records('Purchase Invoice')

View File

@ -16,7 +16,7 @@ class BudgetError(frappe.ValidationError): pass
def get_fiscal_year(date=None, fiscal_year=None, label="Date", verbose=1): def get_fiscal_year(date=None, fiscal_year=None, label="Date", verbose=1):
return get_fiscal_years(date, fiscal_year, label, verbose)[0] return get_fiscal_years(date, fiscal_year, label, verbose)[0]
def get_fiscal_years(date=None, fiscal_year=None, label="Date", verbose=1): def get_fiscal_years(date=None, fiscal_year=None, label="Date", verbose=1):
# if year start date is 2012-04-01, year end date should be 2013-03-31 (hence subdate) # if year start date is 2012-04-01, year end date should be 2013-03-31 (hence subdate)
cond = "" cond = ""
@ -27,16 +27,16 @@ def get_fiscal_years(date=None, fiscal_year=None, label="Date", verbose=1):
(date, date) (date, date)
fy = frappe.db.sql("""select name, year_start_date, year_end_date fy = frappe.db.sql("""select name, year_start_date, year_end_date
from `tabFiscal Year` where %s order by year_start_date desc""" % cond) from `tabFiscal Year` where %s order by year_start_date desc""" % cond)
if not fy: if not fy:
error_msg = """%s %s not in any Fiscal Year""" % (label, formatdate(date)) error_msg = """%s %s not in any Fiscal Year""" % (label, formatdate(date))
error_msg = """{msg}: {date}""".format(msg=_("Fiscal Year does not exist for date"), error_msg = """{msg}: {date}""".format(msg=_("Fiscal Year does not exist for date"),
date=formatdate(date)) date=formatdate(date))
if verbose: frappe.msgprint(error_msg) if verbose: frappe.msgprint(error_msg)
raise FiscalYearError, error_msg raise FiscalYearError, error_msg
return fy return fy
def validate_fiscal_year(date, fiscal_year, label="Date"): def validate_fiscal_year(date, fiscal_year, label="Date"):
years = [f[0] for f in get_fiscal_years(date, label=label)] years = [f[0] for f in get_fiscal_years(date, label=label)]
if fiscal_year not in years: if fiscal_year not in years:
@ -52,14 +52,14 @@ def get_balance_on(account=None, date=None):
if not account and frappe.form_dict.get("account"): if not account and frappe.form_dict.get("account"):
account = frappe.form_dict.get("account") account = frappe.form_dict.get("account")
date = frappe.form_dict.get("date") date = frappe.form_dict.get("date")
cond = [] cond = []
if date: if date:
cond.append("posting_date <= '%s'" % date) cond.append("posting_date <= '%s'" % date)
else: else:
# get balance of all entries that exist # get balance of all entries that exist
date = nowdate() date = nowdate()
try: try:
year_start_date = get_fiscal_year(date, verbose=0)[1] year_start_date = get_fiscal_year(date, verbose=0)[1]
except FiscalYearError, e: except FiscalYearError, e:
@ -71,15 +71,15 @@ def get_balance_on(account=None, date=None):
# this indicates that it is a date older than any existing fiscal year. # this indicates that it is a date older than any existing fiscal year.
# hence, assuming balance as 0.0 # hence, assuming balance as 0.0
return 0.0 return 0.0
acc = frappe.db.get_value('Account', account, \ acc = frappe.db.get_value('Account', account, \
['lft', 'rgt', 'report_type', 'group_or_ledger'], as_dict=1) ['lft', 'rgt', 'report_type', 'group_or_ledger'], as_dict=1)
# for pl accounts, get balance within a fiscal year # for pl accounts, get balance within a fiscal year
if acc.report_type == 'Profit and Loss': if acc.report_type == 'Profit and Loss':
cond.append("posting_date >= '%s' and voucher_type != 'Period Closing Voucher'" \ cond.append("posting_date >= '%s' and voucher_type != 'Period Closing Voucher'" \
% year_start_date) % year_start_date)
# different filter for group and ledger - improved performance # different filter for group and ledger - improved performance
if acc.group_or_ledger=="Group": if acc.group_or_ledger=="Group":
cond.append("""exists ( cond.append("""exists (
@ -88,9 +88,9 @@ def get_balance_on(account=None, date=None):
)""" % (acc.lft, acc.rgt)) )""" % (acc.lft, acc.rgt))
else: else:
cond.append("""gle.account = "%s" """ % (account.replace('"', '\"'), )) cond.append("""gle.account = "%s" """ % (account.replace('"', '\"'), ))
bal = frappe.db.sql(""" bal = frappe.db.sql("""
SELECT sum(ifnull(debit, 0)) - sum(ifnull(credit, 0)) SELECT sum(ifnull(debit, 0)) - sum(ifnull(credit, 0))
FROM `tabGL Entry` gle FROM `tabGL Entry` gle
WHERE %s""" % " and ".join(cond))[0][0] WHERE %s""" % " and ".join(cond))[0][0]
@ -102,7 +102,7 @@ def add_ac(args=None):
if not args: if not args:
args = frappe.local.form_dict args = frappe.local.form_dict
args.pop("cmd") args.pop("cmd")
ac = frappe.get_doc(args) ac = frappe.get_doc(args)
ac.doctype = "Account" ac.doctype = "Account"
ac.old_parent = "" ac.old_parent = ""
@ -115,7 +115,7 @@ def add_cc(args=None):
if not args: if not args:
args = frappe.local.form_dict args = frappe.local.form_dict
args.pop("cmd") args.pop("cmd")
cc = frappe.get_doc(args) cc = frappe.get_doc(args)
cc.doctype = "Cost Center" cc.doctype = "Cost Center"
cc.old_parent = "" cc.old_parent = ""
@ -134,13 +134,14 @@ def reconcile_against_document(args):
'Sales Invoice' : 'against_invoice', 'Sales Invoice' : 'against_invoice',
'Purchase Invoice' : 'against_voucher' 'Purchase Invoice' : 'against_voucher'
} }
d['against_fld'] = against_fld[d['against_voucher_type']] d['against_fld'] = against_fld[d['against_voucher_type']]
# cancel JV # cancel JV
jv_obj = frappe.get_doc('Journal Voucher', d['voucher_no']) jv_obj = frappe.get_doc('Journal Voucher', d['voucher_no'])
jv_obj.make_gl_entries(cancel=1, adv_adj=1) jv_obj.make_gl_entries(cancel=1, adv_adj=1)
# update ref in JV Detail # update ref in JV Detail
update_against_doc(d, jv_obj) update_against_doc(d, jv_obj)
@ -156,13 +157,13 @@ def check_if_jv_modified(args):
check if jv is submitted check if jv is submitted
""" """
ret = frappe.db.sql(""" ret = frappe.db.sql("""
select t2.%(dr_or_cr)s from `tabJournal Voucher` t1, `tabJournal Voucher Detail` t2 select t2.%(dr_or_cr)s from `tabJournal Voucher` t1, `tabJournal Voucher Detail` t2
where t1.name = t2.parent and t2.account = '%(account)s' where t1.name = t2.parent and t2.account = '%(account)s'
and ifnull(t2.against_voucher, '')='' and ifnull(t2.against_voucher, '')=''
and ifnull(t2.against_invoice, '')='' and ifnull(t2.against_jv, '')='' and ifnull(t2.against_invoice, '')='' and ifnull(t2.against_jv, '')=''
and t1.name = '%(voucher_no)s' and t2.name = '%(voucher_detail_no)s' and t1.name = '%(voucher_no)s' and t2.name = '%(voucher_detail_no)s'
and t1.docstatus=1 and t2.%(dr_or_cr)s = %(unadjusted_amt)s""" % args) and t1.docstatus=1 and t2.%(dr_or_cr)s = %(unadjusted_amt)s""" % args)
if not ret: if not ret:
throw(_("""Payment Entry has been modified after you pulled it. Please pull it again.""")) throw(_("""Payment Entry has been modified after you pulled it. Please pull it again."""))
@ -170,15 +171,12 @@ def update_against_doc(d, jv_obj):
""" """
Updates against document, if partial amount splits into rows Updates against document, if partial amount splits into rows
""" """
jv_detail = jv_obj.get("entries", {"name": d["voucher_detail_no"]})[0]
jv_detail.set(d["dr_or_cr"], d["allocated_amt"])
jv_detail.set(d["against_fld"], d["against_voucher"])
frappe.db.sql("""
update `tabJournal Voucher Detail` t1, `tabJournal Voucher` t2
set t1.%(dr_or_cr)s = '%(allocated_amt)s',
t1.%(against_fld)s = '%(against_voucher)s', t2.modified = now()
where t1.name = '%(voucher_detail_no)s' and t1.parent = t2.name""" % d)
if d['allocated_amt'] < d['unadjusted_amt']: if d['allocated_amt'] < d['unadjusted_amt']:
jvd = frappe.db.sql("""select cost_center, balance, against_account, is_advance jvd = frappe.db.sql("""select cost_center, balance, against_account, is_advance
from `tabJournal Voucher Detail` where name = %s""", d['voucher_detail_no']) from `tabJournal Voucher Detail` where name = %s""", d['voucher_detail_no'])
# new entry with balance amount # new entry with balance amount
ch = jv_obj.append("entries") ch = jv_obj.append("entries")
@ -190,90 +188,93 @@ def update_against_doc(d, jv_obj):
ch.against_account = cstr(jvd[0][2]) ch.against_account = cstr(jvd[0][2])
ch.is_advance = cstr(jvd[0][3]) ch.is_advance = cstr(jvd[0][3])
ch.docstatus = 1 ch.docstatus = 1
ch.save(1)
# will work as update after submit
jv_obj.ignore_validate_update_after_submit = True
jv_obj.save()
def get_account_list(doctype, txt, searchfield, start, page_len, filters): def get_account_list(doctype, txt, searchfield, start, page_len, filters):
if not filters.get("group_or_ledger"): if not filters.get("group_or_ledger"):
filters["group_or_ledger"] = "Ledger" filters["group_or_ledger"] = "Ledger"
conditions, filter_values = build_filter_conditions(filters) conditions, filter_values = build_filter_conditions(filters)
return frappe.db.sql("""select name, parent_account from `tabAccount` return frappe.db.sql("""select name, parent_account from `tabAccount`
where docstatus < 2 %s and %s like %s order by name limit %s, %s""" % where docstatus < 2 %s and %s like %s order by name limit %s, %s""" %
(conditions, searchfield, "%s", "%s", "%s"), (conditions, searchfield, "%s", "%s", "%s"),
tuple(filter_values + ["%%%s%%" % txt, start, page_len])) tuple(filter_values + ["%%%s%%" % txt, start, page_len]))
def get_cost_center_list(doctype, txt, searchfield, start, page_len, filters): def get_cost_center_list(doctype, txt, searchfield, start, page_len, filters):
if not filters.get("group_or_ledger"): if not filters.get("group_or_ledger"):
filters["group_or_ledger"] = "Ledger" filters["group_or_ledger"] = "Ledger"
conditions, filter_values = build_filter_conditions(filters) conditions, filter_values = build_filter_conditions(filters)
return frappe.db.sql("""select name, parent_cost_center from `tabCost Center` return frappe.db.sql("""select name, parent_cost_center from `tabCost Center`
where docstatus < 2 %s and %s like %s order by name limit %s, %s""" % where docstatus < 2 %s and %s like %s order by name limit %s, %s""" %
(conditions, searchfield, "%s", "%s", "%s"), (conditions, searchfield, "%s", "%s", "%s"),
tuple(filter_values + ["%%%s%%" % txt, start, page_len])) tuple(filter_values + ["%%%s%%" % txt, start, page_len]))
def remove_against_link_from_jv(ref_type, ref_no, against_field): def remove_against_link_from_jv(ref_type, ref_no, against_field):
linked_jv = frappe.db.sql_list("""select parent from `tabJournal Voucher Detail` linked_jv = frappe.db.sql_list("""select parent from `tabJournal Voucher Detail`
where `%s`=%s and docstatus < 2""" % (against_field, "%s"), (ref_no)) where `%s`=%s and docstatus < 2""" % (against_field, "%s"), (ref_no))
if linked_jv: if linked_jv:
frappe.db.sql("""update `tabJournal Voucher Detail` set `%s`=null, frappe.db.sql("""update `tabJournal Voucher Detail` set `%s`=null,
modified=%s, modified_by=%s modified=%s, modified_by=%s
where `%s`=%s and docstatus < 2""" % (against_field, "%s", "%s", against_field, "%s"), where `%s`=%s and docstatus < 2""" % (against_field, "%s", "%s", against_field, "%s"),
(now(), frappe.session.user, ref_no)) (now(), frappe.session.user, ref_no))
frappe.db.sql("""update `tabGL Entry` frappe.db.sql("""update `tabGL Entry`
set against_voucher_type=null, against_voucher=null, set against_voucher_type=null, against_voucher=null,
modified=%s, modified_by=%s modified=%s, modified_by=%s
where against_voucher_type=%s and against_voucher=%s where against_voucher_type=%s and against_voucher=%s
and voucher_no != ifnull(against_voucher, '')""", and voucher_no != ifnull(against_voucher, '')""",
(now(), frappe.session.user, ref_type, ref_no)) (now(), frappe.session.user, ref_type, ref_no))
frappe.msgprint("{msg} {linked_jv}".format(msg = _("""Following linked Journal Vouchers \ frappe.msgprint("{msg} {linked_jv}".format(msg = _("""Following linked Journal Vouchers \
made against this transaction has been unlinked. You can link them again with other \ made against this transaction has been unlinked. You can link them again with other \
transactions via Payment Reconciliation Tool."""), linked_jv="\n".join(linked_jv))) transactions via Payment Reconciliation Tool."""), linked_jv="\n".join(linked_jv)))
@frappe.whitelist() @frappe.whitelist()
def get_company_default(company, fieldname): def get_company_default(company, fieldname):
value = frappe.db.get_value("Company", company, fieldname) value = frappe.db.get_value("Company", company, fieldname)
if not value: if not value:
throw(_("Please mention default value for '") + throw(_("Please mention default value for '") +
_(frappe.get_meta("Company").get_label(fieldname) + _(frappe.get_meta("Company").get_label(fieldname) +
_("' in Company: ") + company)) _("' in Company: ") + company))
return value return value
def fix_total_debit_credit(): def fix_total_debit_credit():
vouchers = frappe.db.sql("""select voucher_type, voucher_no, vouchers = frappe.db.sql("""select voucher_type, voucher_no,
sum(debit) - sum(credit) as diff sum(debit) - sum(credit) as diff
from `tabGL Entry` from `tabGL Entry`
group by voucher_type, voucher_no group by voucher_type, voucher_no
having sum(ifnull(debit, 0)) != sum(ifnull(credit, 0))""", as_dict=1) having sum(ifnull(debit, 0)) != sum(ifnull(credit, 0))""", as_dict=1)
for d in vouchers: for d in vouchers:
if abs(d.diff) > 0: if abs(d.diff) > 0:
dr_or_cr = d.voucher_type == "Sales Invoice" and "credit" or "debit" dr_or_cr = d.voucher_type == "Sales Invoice" and "credit" or "debit"
frappe.db.sql("""update `tabGL Entry` set %s = %s + %s frappe.db.sql("""update `tabGL Entry` set %s = %s + %s
where voucher_type = %s and voucher_no = %s and %s > 0 limit 1""" % where voucher_type = %s and voucher_no = %s and %s > 0 limit 1""" %
(dr_or_cr, dr_or_cr, '%s', '%s', '%s', dr_or_cr), (dr_or_cr, dr_or_cr, '%s', '%s', '%s', dr_or_cr),
(d.diff, d.voucher_type, d.voucher_no)) (d.diff, d.voucher_type, d.voucher_no))
def get_stock_and_account_difference(account_list=None, posting_date=None): def get_stock_and_account_difference(account_list=None, posting_date=None):
from erpnext.stock.utils import get_stock_balance_on from erpnext.stock.utils import get_stock_balance_on
if not posting_date: posting_date = nowdate() if not posting_date: posting_date = nowdate()
difference = {} difference = {}
account_warehouse = dict(frappe.db.sql("""select name, master_name from tabAccount account_warehouse = dict(frappe.db.sql("""select name, master_name from tabAccount
where account_type = 'Warehouse' and ifnull(master_name, '') != '' where account_type = 'Warehouse' and ifnull(master_name, '') != ''
and name in (%s)""" % ', '.join(['%s']*len(account_list)), account_list)) and name in (%s)""" % ', '.join(['%s']*len(account_list)), account_list))
for account, warehouse in account_warehouse.items(): for account, warehouse in account_warehouse.items():
account_balance = get_balance_on(account, posting_date) account_balance = get_balance_on(account, posting_date)
stock_value = get_stock_balance_on(warehouse, posting_date) stock_value = get_stock_balance_on(warehouse, posting_date)
@ -286,24 +287,24 @@ def validate_expense_against_budget(args):
args = frappe._dict(args) args = frappe._dict(args)
if frappe.db.get_value("Account", {"name": args.account, "report_type": "Profit and Loss"}): if frappe.db.get_value("Account", {"name": args.account, "report_type": "Profit and Loss"}):
budget = frappe.db.sql(""" budget = frappe.db.sql("""
select bd.budget_allocated, cc.distribution_id select bd.budget_allocated, cc.distribution_id
from `tabCost Center` cc, `tabBudget Detail` bd from `tabCost Center` cc, `tabBudget Detail` bd
where cc.name=bd.parent and cc.name=%s and account=%s and bd.fiscal_year=%s where cc.name=bd.parent and cc.name=%s and account=%s and bd.fiscal_year=%s
""", (args.cost_center, args.account, args.fiscal_year), as_dict=True) """, (args.cost_center, args.account, args.fiscal_year), as_dict=True)
if budget and budget[0].budget_allocated: if budget and budget[0].budget_allocated:
yearly_action, monthly_action = frappe.db.get_value("Company", args.company, yearly_action, monthly_action = frappe.db.get_value("Company", args.company,
["yearly_bgt_flag", "monthly_bgt_flag"]) ["yearly_bgt_flag", "monthly_bgt_flag"])
action_for = action = "" action_for = action = ""
if monthly_action in ["Stop", "Warn"]: if monthly_action in ["Stop", "Warn"]:
budget_amount = get_allocated_budget(budget[0].distribution_id, budget_amount = get_allocated_budget(budget[0].distribution_id,
args.posting_date, args.fiscal_year, budget[0].budget_allocated) args.posting_date, args.fiscal_year, budget[0].budget_allocated)
args["month_end_date"] = frappe.db.sql("select LAST_DAY(%s)", args["month_end_date"] = frappe.db.sql("select LAST_DAY(%s)",
args.posting_date)[0][0] args.posting_date)[0][0]
action_for, action = "Monthly", monthly_action action_for, action = "Monthly", monthly_action
elif yearly_action in ["Stop", "Warn"]: elif yearly_action in ["Stop", "Warn"]:
budget_amount = budget[0].budget_allocated budget_amount = budget[0].budget_allocated
action_for, action = "Monthly", yearly_action action_for, action = "Monthly", yearly_action
@ -311,44 +312,44 @@ def validate_expense_against_budget(args):
if action_for: if action_for:
actual_expense = get_actual_expense(args) actual_expense = get_actual_expense(args)
if actual_expense > budget_amount: if actual_expense > budget_amount:
throw(action_for + _(" budget ") + cstr(budget_amount) + throw(action_for + _(" budget ") + cstr(budget_amount) +
_(" for account ") + args.account + _(" against cost center ") + _(" for account ") + args.account + _(" against cost center ") +
args.cost_center + _(" will exceed by ") + args.cost_center + _(" will exceed by ") +
cstr(actual_expense - budget_amount) + _(" after this transaction.") cstr(actual_expense - budget_amount) + _(" after this transaction.")
, exc=BudgetError if action=="Stop" else False) , exc=BudgetError if action=="Stop" else False)
def get_allocated_budget(distribution_id, posting_date, fiscal_year, yearly_budget): def get_allocated_budget(distribution_id, posting_date, fiscal_year, yearly_budget):
if distribution_id: if distribution_id:
distribution = {} distribution = {}
for d in frappe.db.sql("""select bdd.month, bdd.percentage_allocation for d in frappe.db.sql("""select bdd.month, bdd.percentage_allocation
from `tabBudget Distribution Detail` bdd, `tabBudget Distribution` bd from `tabBudget Distribution Detail` bdd, `tabBudget Distribution` bd
where bdd.parent=bd.name and bd.fiscal_year=%s""", fiscal_year, as_dict=1): where bdd.parent=bd.name and bd.fiscal_year=%s""", fiscal_year, as_dict=1):
distribution.setdefault(d.month, d.percentage_allocation) distribution.setdefault(d.month, d.percentage_allocation)
dt = frappe.db.get_value("Fiscal Year", fiscal_year, "year_start_date") dt = frappe.db.get_value("Fiscal Year", fiscal_year, "year_start_date")
budget_percentage = 0.0 budget_percentage = 0.0
while(dt <= getdate(posting_date)): while(dt <= getdate(posting_date)):
if distribution_id: if distribution_id:
budget_percentage += distribution.get(getdate(dt).strftime("%B"), 0) budget_percentage += distribution.get(getdate(dt).strftime("%B"), 0)
else: else:
budget_percentage += 100.0/12 budget_percentage += 100.0/12
dt = add_months(dt, 1) dt = add_months(dt, 1)
return yearly_budget * budget_percentage / 100 return yearly_budget * budget_percentage / 100
def get_actual_expense(args): def get_actual_expense(args):
args["condition"] = " and posting_date<='%s'" % args.month_end_date \ args["condition"] = " and posting_date<='%s'" % args.month_end_date \
if args.get("month_end_date") else "" if args.get("month_end_date") else ""
return frappe.db.sql(""" return frappe.db.sql("""
select sum(ifnull(debit, 0)) - sum(ifnull(credit, 0)) select sum(ifnull(debit, 0)) - sum(ifnull(credit, 0))
from `tabGL Entry` from `tabGL Entry`
where account='%(account)s' and cost_center='%(cost_center)s' where account='%(account)s' and cost_center='%(cost_center)s'
and fiscal_year='%(fiscal_year)s' and company='%(company)s' %(condition)s and fiscal_year='%(fiscal_year)s' and company='%(company)s' %(condition)s
""" % (args))[0][0] """ % (args))[0][0]
def rename_account_for(dt, olddn, newdn, merge, company): def rename_account_for(dt, olddn, newdn, merge, company):
old_account = get_account_for(dt, olddn) old_account = get_account_for(dt, olddn)
if old_account: if old_account:
@ -358,29 +359,29 @@ def rename_account_for(dt, olddn, newdn, merge, company):
new_account = frappe.rename_doc("Account", old_account, newdn) new_account = frappe.rename_doc("Account", old_account, newdn)
else: else:
existing_new_account = get_account_for(dt, newdn) existing_new_account = get_account_for(dt, newdn)
new_account = frappe.rename_doc("Account", old_account, new_account = frappe.rename_doc("Account", old_account,
existing_new_account or newdn, merge=True if existing_new_account else False) existing_new_account or newdn, merge=True if existing_new_account else False)
frappe.db.set_value("Account", new_account or old_account, "master_name", newdn) frappe.db.set_value("Account", new_account or old_account, "master_name", newdn)
def add_abbr_if_missing(dn, company): def add_abbr_if_missing(dn, company):
from erpnext.setup.doctype.company.company import get_name_with_abbr from erpnext.setup.doctype.company.company import get_name_with_abbr
return get_name_with_abbr(dn, company) return get_name_with_abbr(dn, company)
def get_account_for(account_for_doctype, account_for): def get_account_for(account_for_doctype, account_for):
if account_for_doctype in ["Customer", "Supplier"]: if account_for_doctype in ["Customer", "Supplier"]:
account_for_field = "master_type" account_for_field = "master_type"
elif account_for_doctype == "Warehouse": elif account_for_doctype == "Warehouse":
account_for_field = "account_type" account_for_field = "account_type"
return frappe.db.get_value("Account", {account_for_field: account_for_doctype, return frappe.db.get_value("Account", {account_for_field: account_for_doctype,
"master_name": account_for}) "master_name": account_for})
def get_currency_precision(currency=None): def get_currency_precision(currency=None):
if not currency: if not currency:
currency = frappe.db.get_value("Company", currency = frappe.db.get_value("Company",
frappe.db.get_default("company"), "default_currency") frappe.db.get_default("company"), "default_currency")
currency_format = frappe.db.get_value("Currency", currency, "number_format") currency_format = frappe.db.get_value("Currency", currency, "number_format")
from frappe.utils import get_number_format_info from frappe.utils import get_number_format_info
return get_number_format_info(currency_format)[2] return get_number_format_info(currency_format)[2]

View File

@ -10,13 +10,12 @@ test_records = frappe.get_test_records('Lead')
class TestLead(unittest.TestCase): class TestLead(unittest.TestCase):
def test_make_customer(self): def test_make_customer(self):
print "test_make_customer"
from erpnext.selling.doctype.lead.lead import make_customer from erpnext.selling.doctype.lead.lead import make_customer
customer = make_customer("_T-Lead-00001") customer = make_customer("_T-Lead-00001")
self.assertEquals(customer[0]["doctype"], "Customer") self.assertEquals(customer[0]["doctype"], "Customer")
self.assertEquals(customer[0]["lead_name"], "_T-Lead-00001") self.assertEquals(customer[0]["lead_name"], "_T-Lead-00001")
customer[0]["company"] = "_Test Company" customer[0]["company"] = "_Test Company"
customer[0]["customer_group"] = "_Test Customer Group" customer[0]["customer_group"] = "_Test Customer Group"
frappe.get_doc(customer).insert() frappe.get_doc(customer).insert()