Sourced wnframework-modules from Google Code as erpnext

This commit is contained in:
Pratik Vyas
2011-06-08 14:37:15 +05:30
commit c1e6e4c752
1680 changed files with 162635 additions and 0 deletions

View File

@@ -0,0 +1 @@
[{'creation': '2010-07-16 11:03:21', 'doctype': 'Item Group', 'lft': 1, 'owner': 'harshada@webnotestech.com', 'rgt': 286, 'company_abbr': None, 'docstatus': 0, 'item_group_name': 'All Item Groups', 'description': None, 'parent': None, 'is_group': 'Yes', 'company': None, 'show_in_catalogue': None, 'group_or_ledger': None, 'modified_by': 'harshada@webnotestech.com', 'group_name': None, 'trash_reason': None, 'name': 'All Item Groups', 'idx': None, 'modified': '2010-07-16 11:03:21', 'parent_item_group': '', 'old_parent': '', 'parenttype': None, 'parentfield': None}]

View File

@@ -0,0 +1 @@
[{'creation': '2010-07-05 16:08:14', 'doctype': 'Item Group', 'lft': 76, 'owner': 'nabin@webnotestech.com', 'rgt': 77, 'company_abbr': None, 'docstatus': 0, 'item_group_name': 'Default', 'description': None, 'parent': None, 'is_group': 'No', 'company': None, 'show_in_catalogue': None, 'group_or_ledger': None, 'modified_by': 'nabin@webnotestech.com', 'group_name': None, 'trash_reason': None, 'name': 'Default', 'idx': None, 'modified': '2010-07-05 16:08:14', 'parent_item_group': 'All Item Groups', 'old_parent': '', 'parenttype': None, 'parentfield': None}]

View File

@@ -0,0 +1,378 @@
[
{
'creation': '2010-09-25 10:50:35',
'disabled': 'No',
'docstatus': 0,
'doctype': u'Module Def',
'doctype_list': None,
'file_list': None,
'idx': None,
'is_hidden': None,
'last_updated_date': '2010-11-29 12:02:02',
'modified': '2011-04-19 11:49:10',
'modified_by': 'Administrator',
'module_desc': 'Material Management',
'module_icon': 'Stock.gif',
'module_label': 'Stock',
'module_name': 'Material Management',
'module_page': None,
'module_seq': 6,
'name': 'Material Management',
'owner': 'Administrator',
'parent': None,
'parentfield': None,
'parenttype': None,
'trash_reason': None,
'widget_code': None
},
{
'click_function': None,
'creation': '2010-09-25 10:50:35',
'description': 'Item master',
'display_name': 'Item',
'doc_name': 'Item',
'doc_type': 'Forms',
'docstatus': 0,
'doctype': 'Module Def Item',
'fields': 'name\nitem_group\ndescription',
'hide': None,
'icon': None,
'idx': 1,
'modified': '2011-05-09 11:04:26',
'modified_by': 'Administrator',
'name': 'MDI01077',
'owner': 'Administrator',
'parent': 'Material Management',
'parentfield': 'items',
'parenttype': 'Module Def'
},
{
'click_function': None,
'creation': '2010-09-25 10:50:35',
'description': 'Record of items added, removed or moved from one warehouse to another.',
'display_name': 'Stock Entry',
'doc_name': 'Stock Entry',
'doc_type': 'Forms',
'docstatus': 0,
'doctype': 'Module Def Item',
'fields': 'transfer_date\npurpose\nfrom_warehouse\nto_warehouse\nremarks',
'hide': None,
'icon': None,
'idx': 2,
'modified': '2011-05-09 11:04:26',
'modified_by': 'Administrator',
'name': 'MDI01078',
'owner': 'Administrator',
'parent': 'Material Management',
'parentfield': 'items',
'parenttype': 'Module Def'
},
{
'click_function': None,
'creation': '2010-09-25 10:50:35',
'description': 'Record of items delivered to your customers along with the Printed Note',
'display_name': 'Delivery Note',
'doc_name': 'Delivery Note',
'doc_type': 'Forms',
'docstatus': 0,
'doctype': 'Module Def Item',
'fields': 'status\ntransaction_date\ncustomer\nterritory\ngrand_total\nper_billed',
'hide': None,
'icon': None,
'idx': 3,
'modified': '2011-05-09 11:04:26',
'modified_by': 'Administrator',
'name': 'MDI01079',
'owner': 'Administrator',
'parent': 'Material Management',
'parentfield': 'items',
'parenttype': 'Module Def'
},
{
'click_function': None,
'creation': '2010-09-25 10:50:35',
'description': 'Record of incoming material from your suppliers',
'display_name': 'Purchase Receipt',
'doc_name': 'Purchase Receipt',
'doc_type': 'Forms',
'docstatus': 0,
'doctype': 'Module Def Item',
'fields': 'status\ntransaction_date\nsupplier\ngrand_total\nper_billed',
'hide': None,
'icon': None,
'idx': 4,
'modified': '2011-05-09 11:04:26',
'modified_by': 'Administrator',
'name': 'MDI01080',
'owner': 'Administrator',
'parent': 'Material Management',
'parentfield': 'items',
'parenttype': 'Module Def'
},
{
'click_function': None,
'creation': '2010-09-25 10:50:35',
'description': 'Details of Installation done after delivery',
'display_name': 'Installation Note',
'doc_name': 'Installation Note',
'doc_type': 'Forms',
'docstatus': 0,
'doctype': 'Module Def Item',
'fields': None,
'hide': None,
'icon': None,
'idx': 5,
'modified': '2011-05-09 11:04:26',
'modified_by': 'Administrator',
'name': 'MDI01081',
'owner': 'Administrator',
'parent': 'Material Management',
'parentfield': 'items',
'parenttype': 'Module Def'
},
{
'click_function': None,
'creation': '2010-09-25 10:50:35',
'description': 'Create Quality Inspection Report for any item',
'display_name': 'Inspection Report',
'doc_name': 'QA Inspection Report',
'doc_type': 'Forms',
'docstatus': 0,
'doctype': 'Module Def Item',
'fields': 'inspection_type\nitem_code\nreport_date\npurchase_receipt_no\ndelivery_note_no',
'hide': None,
'icon': None,
'idx': 6,
'modified': '2011-05-09 11:04:26',
'modified_by': 'Administrator',
'name': 'MDI01082',
'owner': 'nabin@webnotestech.com',
'parent': 'Material Management',
'parentfield': 'items',
'parenttype': 'Module Def'
},
{
'click_function': None,
'creation': '2010-09-25 10:50:35',
'description': 'Reconcile your stock by uploading it form an excel file',
'display_name': 'Stock Reconciliation',
'doc_name': 'Stock Reconciliation',
'doc_type': 'Forms',
'docstatus': 0,
'doctype': 'Module Def Item',
'fields': 'reconciliation_date\nreconciliation_time\nremark',
'hide': None,
'icon': None,
'idx': 7,
'modified': '2011-05-09 11:04:26',
'modified_by': 'Administrator',
'name': 'MDI01083',
'owner': 'Administrator',
'parent': 'Material Management',
'parentfield': 'items',
'parenttype': 'Module Def'
},
{
'click_function': None,
'creation': '2010-09-25 10:50:35',
'description': 'This utility tool will update Stock UOM in Item and will respectively update Actual Qty in Stock Ledger as per Conversion Factor.',
'display_name': 'Stock UOM Replace Utility',
'doc_name': 'Stock UOM Replace Utility',
'doc_type': 'Single DocType',
'docstatus': 0,
'doctype': 'Module Def Item',
'fields': None,
'hide': None,
'icon': None,
'idx': 8,
'modified': '2011-05-09 11:04:26',
'modified_by': 'Administrator',
'name': 'MDI01084',
'owner': 'jai@webnotestech.com',
'parent': 'Material Management',
'parentfield': 'items',
'parenttype': 'Module Def'
},
{
'click_function': None,
'creation': '2010-09-25 10:50:35',
'description': 'This utility will help in tracking stock for Sales Return and Purchase Return.',
'display_name': 'Sales and Purchase Return Wizard',
'doc_name': 'Sales and Purchase Return Wizard',
'doc_type': 'Single DocType',
'docstatus': 0,
'doctype': 'Module Def Item',
'fields': None,
'hide': None,
'icon': None,
'idx': 9,
'modified': '2011-05-09 11:04:26',
'modified_by': 'Administrator',
'name': 'MDI01085',
'owner': 'jai@webnotestech.com',
'parent': 'Material Management',
'parentfield': 'items',
'parenttype': 'Module Def'
},
{
'click_function': None,
'creation': '2010-09-25 10:50:35',
'description': None,
'display_name': 'Stock Ledger',
'doc_name': 'Stock Ledger Entry',
'doc_type': 'Reports',
'docstatus': 0,
'doctype': 'Module Def Item',
'fields': None,
'hide': None,
'icon': None,
'idx': 10,
'modified': '2011-05-09 11:04:26',
'modified_by': 'Administrator',
'name': 'MDI01088',
'owner': 'Administrator',
'parent': 'Material Management',
'parentfield': 'items',
'parenttype': 'Module Def'
},
{
'click_function': None,
'creation': '2010-09-25 10:50:35',
'description': None,
'display_name': 'Stock Level',
'doc_name': 'Bin',
'doc_type': 'Reports',
'docstatus': 0,
'doctype': 'Module Def Item',
'fields': None,
'hide': None,
'icon': None,
'idx': 11,
'modified': '2011-05-09 11:04:26',
'modified_by': 'Administrator',
'name': 'MDI01089',
'owner': 'Administrator',
'parent': 'Material Management',
'parentfield': 'items',
'parenttype': 'Module Def'
},
{
'click_function': None,
'creation': '2010-09-25 10:50:35',
'description': None,
'display_name': 'Shortage To Indent',
'doc_name': 'Item',
'doc_type': 'Reports',
'docstatus': 0,
'doctype': 'Module Def Item',
'fields': None,
'hide': None,
'icon': None,
'idx': 12,
'modified': '2011-05-09 11:04:26',
'modified_by': 'Administrator',
'name': 'MDI01090',
'owner': 'Administrator',
'parent': 'Material Management',
'parentfield': 'items',
'parenttype': 'Module Def'
},
{
'click_function': None,
'creation': '2010-09-25 10:50:35',
'description': 'Stock Value as per Item and Warehouse',
'display_name': 'Stock Report',
'doc_name': 'Stock Ledger Entry',
'doc_type': 'Reports',
'docstatus': 0,
'doctype': 'Module Def Item',
'fields': None,
'hide': None,
'icon': None,
'idx': 13,
'modified': '2011-05-09 11:04:26',
'modified_by': 'Administrator',
'name': 'MDI01091',
'owner': 'Administrator',
'parent': 'Material Management',
'parentfield': 'items',
'parenttype': 'Module Def'
},
{
'click_function': None,
'creation': '2010-09-25 10:50:35',
'description': None,
'display_name': 'Stock Aging Report',
'doc_name': 'Serial No',
'doc_type': 'Reports',
'docstatus': 0,
'doctype': 'Module Def Item',
'fields': None,
'hide': None,
'icon': None,
'idx': 14,
'modified': '2011-05-09 11:04:26',
'modified_by': 'Administrator',
'name': 'MDI01092',
'owner': 'ashwini@webnotestech.com',
'parent': 'Material Management',
'parentfield': 'items',
'parenttype': 'Module Def'
},
{
'creation': '2010-09-25 10:50:35',
'docstatus': 0,
'doctype': 'Module Def Role',
'idx': 1,
'modified': '2010-09-25 10:50:35',
'modified_by': 'Administrator',
'name': 'MDR00292',
'owner': 'Administrator',
'parent': 'Material Management',
'parentfield': 'roles',
'parenttype': 'Module Def',
'role': 'Material User'
},
{
'creation': '2010-09-25 10:50:35',
'docstatus': 0,
'doctype': 'Module Def Role',
'idx': 2,
'modified': '2010-09-25 10:50:35',
'modified_by': 'Administrator',
'name': 'MDR00293',
'owner': 'Administrator',
'parent': 'Material Management',
'parentfield': 'roles',
'parenttype': 'Module Def',
'role': 'Material Master Manager'
},
{
'creation': '2010-09-25 10:50:35',
'docstatus': 0,
'doctype': 'Module Def Role',
'idx': 3,
'modified': '2010-09-25 10:50:35',
'modified_by': 'Administrator',
'name': 'MDR00294',
'owner': 'Administrator',
'parent': 'Material Management',
'parentfield': 'roles',
'parenttype': 'Module Def',
'role': 'Material Manager'
},
{
'creation': '2010-09-25 10:50:35',
'docstatus': 0,
'doctype': 'Module Def Role',
'idx': 4,
'modified': '2010-09-25 10:50:35',
'modified_by': 'Administrator',
'name': 'MDR00295',
'owner': 'nabin@webnotestech.com',
'parent': 'Material Management',
'parentfield': 'roles',
'parenttype': 'Module Def',
'role': 'Quality Manager'
}
]

View File

@@ -0,0 +1 @@
[{'modified_by': 'Administrator', 'name': 'Purchase Receipt Format', 'parent': None, 'creation': '2009-03-12 12:10:22', 'modified': '2009-09-07 11:03:11', 'module': 'Material Management', 'doctype': 'Print Format', 'idx': None, 'parenttype': None, 'html': '<html>\n<head>\n<!--Other charges function-->\n<script>\n var make_row = function(title,val,bold){\n var bstart = \'<b>\'; var bend = \'</b>\';\n return \'<tr><td style="width:50%">\'+(bold?bstart:\'\')+title+(bold?bend:\'\')+\'</td>\'\n +\'<td style="width:20%;text-align:right">\'+doc.currency+\'</td>\'\n +\'<td style="width:30%;text-align:right">\'+(val?val:\'0.00\')+\'</td>\'\n +\'</tr>\'\n }\n\n function get_other_charges(){\n var out =\'\';\n out += \'<div><table class="noborder" style="width:100%">\';\n out += make_row(\'Total Amount\',fmt_money(convert_rate(doc.total_amount)),1)\n +make_row(\'Grand Total\',fmt_money(convert_rate(doc.grand_total)),1);\n out += \'</table></div>\';\n return out;\n }\n\n function get_buying_costs(){\n var out =\'\';\n if(doc.buying_cost_transport || doc.buying_cost_taxes || doc.buying_cost_other){\n out += \'<div><table class="noborder" style="width:100%">\'\n + \'<tr><td style="width:100%"><b>\'+\'Buying Cost Details\'+\'</b></td></tr>\';\n if(doc.buying_cost_transport){ out += make_row(\'Transport Cost\',fmt_money(convert_rate(doc.buying_cost_transport)),0)}\n if(doc.buying_cost_taxes){ out += make_row(\'Taxes\',fmt_money(convert_rate(doc.buying_cost_taxes)),0)}\n if(doc.buying_cost_other){ out += make_row(\'Other Cost\',fmt_money(convert_rate(doc.buying_cost_other)),0)}\n out += \'</table></div>\';\n }\n return out;\n }\n\n function get_letter_head(){\n var cp = locals[\'Control Panel\'][\'Control Panel\'];\n \tif(cp.letter_head) {return cp.letter_head; }\n }\n \n function convert_rate(val){\n var new_val = flt(val)/flt(doc.conversion_rate);\n return new_val;\n }\n \n function get_transport_details(){\n var out = \'\';\n if(doc.transporter_name || doc.lr_no || doc.lr_date){\n out += \'<div><table class="noborder" style="width:40%">\'\n +\'<tr><td style="width:80%"><b>\' + \'Transporter Details\'+\'</b></td><td style="width:20%"></td></tr>\'\n\n if(doc.transporter_name){ out += \'<tr><td style="width:40%">\' + \'Transporter Name\'+\'</td><td style="width:60%">\'+doc.transporter_name+\'</td></tr>\'}\n if(doc.lr_no){ out += \'<tr><td style="width:40%">\' + \'LR No\'+\'</td><td style="width:60%">\'+doc.lr_no+\'</td></tr>\'}\n if(doc.lr_date){ out += \'<tr><td style="width:40%">\' + \'LR Date\'+\'</td><td style="width:60%">\'+doc.lr_date+\'</td></tr>\'}\n out += \'</table></div>\'\n }\n return out;\n }\n\n</script>\n</head>\n<body>\n<div style="border:1px solid black;padding:15px">\n<!--header-->\n<div><script>get_letter_head()</script></div>\n<div style="border-bottom: 1px solid; padding-bottom: 5px;">\n <div><br><b>Purchase Receipt: <script>doc.name</script></b></div>\n <div>Date: <script>date.str_to_user(doc.transaction_date)</script></div>\n</div>\n\n<div style="padding-top:15px">\n<div><script>doc.supplier</script></div>\n<div><br><script>replace_newlines(doc.supplier_address)</script></div>\n</div>\n\n<div>\n<br>\n <script>\n var t = print_table(\'Purchase Receipt\', doc.name, \'purchase_receipt_details\', \'Purchase Receipt Detail\', [\'SR\', \'item_code\',\'description\',\'received_qty\',\'qty\',\'rejected_qty\',\'po_rate\',\'amount\',\'billed_qty\'], [\'Sr\', \'Item Code\', \'Description\',\'Received Quantity\',\'Accepted Qty\',\'Rejected Qty\',\'Rate\',\'Amount\',\'Billed Qty\'], [\'4%\',\'12%\', \'24%\', \'10%\',\'10%\',\'10%\',\'10%\',\'10%\',\'10%\'])\n if(t.appendChild) {\n // single\n out = t.innerHTML;\n } \n else {//multiple\n out = \'\'\n for(var i=0;i<t.length;i++) {\n if(i!=t.length-1){\n out += \'<div style:"padding-top:5px;"></div>\' + t[i].innerHTML +\'<div style="page-break-after:always"></div>\';\n }\n else out += \'<div style:"padding-top:5px;"></div>\' + t[i].innerHTML;\n }\n }\n out;\n </script>\n\n</div>\n\n<!--Other charges table-->\n<div>\n<table style="width:100%">\n <tr><td style="width:40%"><script>get_buying_costs()</script></td>\n <td style="width:20%"></td><td style="width:40%"><script>get_other_charges()</script></td></tr>\n</table>\n</div>\n<div><script>get_transport_details()</script></div>\n<div><br>Payment Terms</div>\n<div><br><script>replace_newlines(doc.payment_terms)</script></div>\n<div><br>For NCSCI</div>\n<div><br><br>(Authorised Signatory)</div>\n</div></body>\n</html>', 'owner': 'Administrator', 'docstatus': 0, 'standard': 'Yes', 'parentfield': None}]

View File

View File

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,294 @@
# Please edit this list and import only required elements
import webnotes
from webnotes.utils import add_days, add_months, add_years, cint, cstr, date_diff, default_fields, flt, fmt_money, formatdate, generate_hash, getTraceback, get_defaults, get_first_day, get_last_day, getdate, has_common, month_name, now, nowdate, replace_newlines, sendmail, set_default, str_esc_quote, user_format, validate_email_add
from webnotes.model import db_exists
from webnotes.model.doc import Document, addchild, removechild, getchildren, make_autoname, SuperDocType
from webnotes.model.doclist import getlist, copy_doclist
from webnotes.model.code import get_obj, get_server_obj, run_server_obj, updatedb, check_syntax
from webnotes import session, form, is_testing, msgprint, errprint
set = webnotes.conn.set
sql = webnotes.conn.sql
get_value = webnotes.conn.get_value
in_transaction = webnotes.conn.in_transaction
convert_to_lists = webnotes.conn.convert_to_lists
# -----------------------------------------------------------------------------------------
class DocType:
def __init__(self, doc, doclist=[]):
self.doc = doc
self.doclist = doclist
# -------------
# stock update
# -------------
def update_stock(self, actual_qty=0, reserved_qty=0, ordered_qty=0, indented_qty=0, planned_qty=0, dt=None, sle_id='', posting_time='', serial_no = ''):
if not dt: dt = nowdate()
# update the stock values (for current quantities)
self.doc.actual_qty = flt(self.doc.actual_qty) + flt(actual_qty)
self.doc.ordered_qty = flt(self.doc.ordered_qty) + flt(ordered_qty)
self.doc.reserved_qty = flt(self.doc.reserved_qty) + flt(reserved_qty)
self.doc.indented_qty = flt(self.doc.indented_qty) + flt(indented_qty)
self.doc.planned_qty = flt(self.doc.planned_qty) + flt(planned_qty)
self.doc.projected_qty = flt(self.doc.actual_qty) + flt(self.doc.ordered_qty) + flt(self.doc.indented_qty) + flt(self.doc.planned_qty) - flt(self.doc.reserved_qty)
self.doc.save()
# update valuation for post dated entry
if actual_qty:
prev_sle = self.get_prev_sle(sle_id, dt, posting_time, serial_no)
cqty = flt(prev_sle.get('bin_aqat', 0))
# Block if actual qty becomes negative
if (flt(cqty) + flt(actual_qty)) < 0 and flt(actual_qty) < 0:
msgprint('Not enough quantity (requested: %s, current: %s) for Item <b>%s</b> in Warehouse <b>%s</b> as on %s %s' % (flt(actual_qty), flt(cqty), self.doc.item_code, self.doc.warehouse, dt, posting_time), raise_exception = 1)
self.update_item_valuation(sle_id, dt, posting_time, serial_no, prev_sle)
# --------------------------------
# get first stock ledger entry
# --------------------------------
def get_first_sle(self):
sle = sql("""
select * from `tabStock Ledger Entry`
where item_code = %s
and warehouse = %s
order by timestamp(posting_date, posting_time) asc, name asc
limit 1
""", (self.doc.item_code, self.doc.warehouse), as_dict=1)
return sle and sle[0] or None
# --------------------------------
# get previous stock ledger entry
# --------------------------------
def get_prev_sle(self, sle_id, posting_date, posting_time, serial_no = ''):
# this function will only be called for a live entry
# for which the "name" will be the latest (even for the same timestamp)
# and even for a back-dated entry
# hence there cannot be any "backdated entries" with a name greater than the
# current one
# if there are multiple entries on this timestamp, then the last one will be with
# the last "name"
# else, the last entry will be the highest name at the previous timestamp
# hence, the double sort on timestamp and name should be sufficient condition
# to get the last sle
sle = sql("""
select * from `tabStock Ledger Entry`
where item_code = %s
and warehouse = %s
and name != %s
and timestamp(posting_date, posting_time) <= timestamp(%s, %s)
order by timestamp(posting_date, posting_time) desc, name desc
limit 1
""", (self.doc.item_code, self.doc.warehouse, sle_id, posting_date, posting_time), as_dict=1)
return sle and sle[0] or {}
# --------------------------------------------------------------------------------------------------------------------------------------
# validate negative stock (validate if stock is going -ve in between for back dated entries will consider only is_cancel = 'No' entries)
# --------------------------------------------------------------------------------------------------------------------------------------
def validate_negative_stock(self, cqty, s):
if cqty + s['actual_qty'] < 0 and s['is_cancelled'] != 'Yes':
msgprint(cqty)
msgprint(s['actual_qty'])
msgprint('Cannot complete this transaction because stock will become negative for Item <b>%s</b> in Warehouse <b>%s</b> on Posting Date <b>%s</b>' % \
(self.doc.item_code, self.doc.warehouse, s['posting_date']))
raise Exception
# ------------------------------------
# get serialized inventory values
# ------------------------------------
def get_serialized_inventory_values(self, val_rate, in_rate, opening_qty, actual_qty, is_cancelled, serial_nos):
if flt(in_rate) < 0: # wrong incoming rate
in_rate = val_rate
elif flt(in_rate) == 0: # In case of delivery/stock issue, get average purchase rate of serial nos of current entry
in_rate = flt(sql("select ifnull(avg(purchase_rate), 0) from `tabSerial No` where name in (%s)" % (serial_nos))[0][0])
if in_rate and val_rate == 0: # First entry
val_rate = in_rate
# val_rate is same as previous entry if val_rate is negative
# Otherwise it will be calculated as per moving average
elif opening_qty + actual_qty > 0 and ((opening_qty * val_rate) + (actual_qty * in_rate)) > 0:
val_rate = ((opening_qty *val_rate) + (actual_qty * in_rate)) / (opening_qty + actual_qty)
stock_val = val_rate
return val_rate, stock_val
# ------------------------------------
# get moving average inventory values
# ------------------------------------
def get_moving_average_inventory_values(self, val_rate, in_rate, opening_qty, actual_qty, is_cancelled):
if flt(in_rate) <= 0: # In case of delivery/stock issue in_rate = 0 or wrong incoming rate
in_rate = val_rate
if in_rate and val_rate == 0: # First entry
val_rate = in_rate
# val_rate is same as previous entry if :
# 1. actual qty is negative(delivery note / stock entry)
# 2. cancelled entry
# 3. val_rate is negative
# Otherwise it will be calculated as per moving average
elif actual_qty > 0 and (opening_qty + actual_qty) > 0 and is_cancelled == 'No' and ((opening_qty * val_rate) + (actual_qty * in_rate)) > 0:
val_rate = ((opening_qty *val_rate) + (actual_qty * in_rate)) / (opening_qty + actual_qty)
stock_val = val_rate
return val_rate, stock_val
# --------------------------
# get fifo inventory values
# --------------------------
def get_fifo_inventory_values(self, val_rate, in_rate, actual_qty, incoming_rate):
# add batch to fcfs balance
if actual_qty > 0:
self.fcfs_bal.append([flt(actual_qty), flt(in_rate)])
val_rate = incoming_rate
# remove from fcfs balance
else:
fcfs_val = 0
withdraw = flt(abs(actual_qty))
while withdraw:
if not self.fcfs_bal:
break # nothing in store
batch = self.fcfs_bal[0]
if batch[0] < withdraw:
# not enough in current batch, clear batch
withdraw -= batch[0]
fcfs_val += (flt(batch[0]) * flt(batch[1]))
self.fcfs_bal.pop(0)
else:
# all from current batch
fcfs_val += (flt(withdraw) * flt(batch[1]))
batch[0] -= withdraw
withdraw = 0
val_rate = flt(fcfs_val) / flt(abs(actual_qty))
return val_rate
# -------------------
# get valuation rate
# -------------------
def get_valuation_rate(self, val_method, serial_nos, val_rate, in_rate, stock_val, cqty, s):
if serial_nos:
val_rate, stock_val = self.get_serialized_inventory_values(val_rate, in_rate, opening_qty = cqty, actual_qty = s['actual_qty'], is_cancelled = s['is_cancelled'], serial_nos = serial_nos)
elif val_method == 'Moving Average':
val_rate, stock_val = self.get_moving_average_inventory_values(val_rate, in_rate, opening_qty = cqty, actual_qty = s['actual_qty'], is_cancelled = s['is_cancelled'])
elif val_method == 'FIFO':
val_rate = self.get_fifo_inventory_values(val_rate, in_rate, actual_qty = s['actual_qty'], incoming_rate = s['incoming_rate'])
return val_rate, stock_val
# ----------------
# get stock value
# ----------------
def get_stock_value(self, val_method, cqty, stock_val, serial_nos):
if val_method == 'Moving Average' or serial_nos:
stock_val = flt(stock_val) * flt(cqty)
elif val_method == 'FIFO':
for d in self.fcfs_bal:
stock_val += (flt(d[0]) * flt(d[1]))
return stock_val
# ----------------------
# update item valuation
# ----------------------
def update_item_valuation(self, sle_id=None, posting_date=None, posting_time=None, serial_no=None, prev_sle=None):
# no sle given, start from the first one (for repost)
if not prev_sle:
cqty, cval, val_rate, self.fcfs_bal = 0, 0, 0, []
# normal
else:
cqty = flt(prev_sle.get('bin_aqat', 0))
cval =flt(prev_sle.get('stock_value', 0))
val_rate = flt(prev_sle.get('valuation_rate', 0))
self.fcfs_bal = eval(prev_sle.get('fcfs_stack', '[]') or '[]')
val_method = get_obj('Valuation Control').get_valuation_method(self.doc.item_code) # get valuation method
# recalculate the balances for all stock ledger entries
# after this one (so that the corrected balance will reflect
# correctly in all entries after this one)
sll = sql("""
select *
from `tabStock Ledger Entry`
where item_code = %s
and warehouse = %s
and timestamp(posting_date, posting_time) > timestamp(%s, %s)
order by timestamp(posting_date, posting_time) asc, name asc""", \
(self.doc.item_code, self.doc.warehouse, posting_date, posting_time), as_dict = 1)
# if in live entry - update the values of the current sle
if sle_id:
sll = sql("select * from `tabStock Ledger Entry` where name=%s", sle_id, as_dict=1) + sll
for s in sll:
# block if stock level goes negative on any date
self.validate_negative_stock(cqty, s)
stock_val, in_rate = 0, s['incoming_rate'] # IN
serial_nos = "'"+"', '".join(cstr(s["serial_no"]).split('\n')) + "'"
# Get valuation rate
val_rate, stock_val = self.get_valuation_rate(val_method, serial_nos, val_rate, in_rate, stock_val, cqty, s)
# Qty upto the sle
cqty += s['actual_qty']
# Stock Value upto the sle
stock_val = self.get_stock_value(val_method, cqty, stock_val, serial_nos)
# update current sle --> will it be good to update incoming rate in sle for outgoing stock entry?????
sql("""update `tabStock Ledger Entry`
set bin_aqat=%s, valuation_rate=%s, fcfs_stack=%s, stock_value=%s
where name=%s""", (cqty, flt(val_rate), cstr(self.fcfs_bal), stock_val, s['name']))
# update the bin
if sll:
sql("update `tabBin` set valuation_rate=%s, actual_qty=%s, stock_value = %s where name=%s", \
(flt(val_rate), cqty, flt(stock_val), self.doc.name))
# item re-order
# -------------
def reorder_item(self):
projected_qty = flt(self.doc.actual_qty) + flt(self.doc.indented_qty) + flt(self.doc.ordered_qty)
item_reorder_level = sql("select reorder_level from `%sItem` where name = '%s'" % (self.prefix, self.doc.item_code))[0][0] or 0
if flt(item_reorder_level) > flt(projected_qty):
msgprint("Item: " + self.doc.item_code + " is to be re-ordered. Indent raised (Not Implemented).")
# validate
def validate(self):
self.validate_mandatory()
# item re-order
# -------------
def reorder_item(self):
#check if re-order is required
projected_qty = flt(self.doc.actual_qty) + flt(self.doc.indented_qty) + flt(self.doc.ordered_qty)
item_reorder_level = sql("select reorder_level from `%sItem` where name = '%s'" % (self.prefix, self.doc.item_code))[0][0] or 0
if flt(item_reorder_level) > flt(projected_qty):
msgprint("Item: " + self.doc.item_code + " is to be re-ordered. Indent raised (Not Implemented).")
# validate
def validate(self):
self.validate_mandatory()
# set defaults in bin
def validate_mandatory(self):
qf = ['actual_qty', 'reserved_qty', 'ordered_qty', 'indented_qty']
for f in qf:
if (not self.doc.fields.has_key(f)) or (not self.doc.fields[f]):
self.doc.fields[f] = 0.0

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,361 @@
// Module Material Management
cur_frm.cscript.tname = "Delivery Note Detail";
cur_frm.cscript.fname = "delivery_note_details";
cur_frm.cscript.other_fname = "other_charges";
cur_frm.cscript.sales_team_fname = "sales_team";
$import(Sales Common)
$import(Other Charges)
$import(SMS Control)
// ONLOAD
// ================================================================================================
cur_frm.cscript.onload = function(doc, dt, dn) {
if(!doc.status) set_multiple(dt,dn,{status:'Draft'});
if(!doc.transaction_date) set_multiple(dt,dn,{transaction_date:get_today()});
if(!doc.posting_date) set_multiple(dt,dn,{posting_date:get_today()});
if(doc.__islocal && doc.customer) cur_frm.cscript.pull_item_details_onload(doc,dt,dn);
if(!doc.posting_time) doc.posting_time = wn.datetime.get_cur_time()
if(doc.__islocal){
hide_field(['customer_address','contact_person','customer_name','address_display','contact_display','contact_mobile','contact_email','territory','customer_group']);
}
}
cur_frm.cscript.onload_post_render = function(doc, dt, dn) {
// load default charges
if(doc.__islocal && !getchildren('RV Tax Detail', doc.name, 'other_charges', doc.doctype).length)
cur_frm.cscript.load_taxes(doc, cdt, cdn);
}
// REFRESH
// ================================================================================================
cur_frm.cscript.refresh = function(doc, cdt, cdn) {
cur_frm.clear_custom_buttons();
var ch = getchildren('Delivery Note Detail',doc.name,'delivery_note_details');
var is_billed = 1; // assume all qty's are billed
var is_installed = 1; //assume all qty's are installed
for(var i in ch){
if(ch[i].billed_qty < ch[i].qty) is_billed = 0;
if(ch[i].installed_qty < ch[i].qty) is_installed = 0;
if(ch[i].billed_amt < ch[i].amount) is_billed = 0;
}
if(is_billed==0 && doc.docstatus==1) cur_frm.add_custom_button('Make Invoice', cur_frm.cscript['Make Sales Invoice']);
if(is_installed==0 && doc.docstatus==1) cur_frm.add_custom_button('Make Installation Note', cur_frm.cscript['Make Installation Note']);
if (doc.docstatus!=1) {
hide_field(['SMS', 'Send SMS', 'message', 'customer_mobile_no', 'Repair Delivery Note']);
} else {
cur_frm.add_custom_button('Send SMS', cur_frm.cscript['Send SMS']);
unhide_field(['SMS','Send SMS', 'message', 'customer_mobile_no', 'Repair Delivery Note']);
}
set_print_hide(doc, cdt, cdn);
}
//customer
cur_frm.cscript.customer = function(doc,dt,dn) {
var callback = function(r,rt) {
var doc = locals[cur_frm.doctype][cur_frm.docname];
cur_frm.refresh();
}
if(doc.customer) $c_obj(make_doclist(doc.doctype, doc.name), 'get_default_customer_shipping_address', '', callback);
if(doc.customer) unhide_field(['customer_address','contact_person','customer_name','address_display','contact_display','contact_mobile','contact_email','territory','customer_group','shipping_address']);
}
cur_frm.cscript.customer_address = cur_frm.cscript.contact_person = function(doc,dt,dn) {
if(doc.customer) get_server_fields('get_customer_address', JSON.stringify({customer: doc.customer, address: doc.customer_address, contact: doc.contact_person}),'', doc, dt, dn, 1);
}
cur_frm.fields_dict.customer_address.on_new = function(dn) {
locals['Address'][dn].customer = locals[cur_frm.doctype][cur_frm.docname].customer;
locals['Address'][dn].customer_name = locals[cur_frm.doctype][cur_frm.docname].customer_name;
}
cur_frm.fields_dict.contact_person.on_new = function(dn) {
locals['Contact'][dn].customer = locals[cur_frm.doctype][cur_frm.docname].customer;
locals['Contact'][dn].customer_name = locals[cur_frm.doctype][cur_frm.docname].customer_name;
}
cur_frm.fields_dict['customer_address'].get_query = function(doc, cdt, cdn) {
return 'SELECT name,address_line1,city FROM tabAddress WHERE customer = "'+ doc.customer +'" AND docstatus != 2 AND name LIKE "%s" ORDER BY name ASC LIMIT 50';
}
cur_frm.fields_dict['contact_person'].get_query = function(doc, cdt, cdn) {
return 'SELECT name,CONCAT(first_name," ",ifnull(last_name,"")) As FullName,department,designation FROM tabContact WHERE customer = "'+ doc.customer +'" AND docstatus != 2 AND name LIKE "%s" ORDER BY name ASC LIMIT 50';
}
cur_frm.cscript['Get Items'] = function(doc,dt,dn) {
var callback = function(r,rt){
var doc = locals[cur_frm.doctype][cur_frm.docname];
if(r.message){
doc.sales_order_no = r.message;
if(doc.sales_order_no) {
unhide_field(['customer_address','contact_person','customer_name','address_display','contact_display','contact_mobile','contact_email','territory','customer_group']);
}
refresh_many(['delivery_note_details','customer','customer_address','contact_person','customer_name','address_display','contact_display','contact_mobile','contact_email','territory','customer_group']);
}
}
$c_obj(make_doclist(doc.doctype, doc.name),'pull_sales_order_details','',callback);
}
//RV-DN : Pull Item details - UOM, Item Group as it was not in Sales Invoice
//---------------------------------------------------------------------
cur_frm.cscript.pull_item_details_onload = function(doc,dt,dn){
var callback = function(r,rt){
refresh_field('delivery_note_details');
cur_frm.cscript.customer(doc,dt,dn);
}
$c_obj(make_doclist(dt,dn),'set_item_details','',callback);
}
//================ create new contact ============================================================================
cur_frm.cscript.new_contact = function(){
tn = createLocal('Contact');
locals['Contact'][tn].is_customer = 1;
if(doc.customer) locals['Contact'][tn].customer = doc.customer;
loaddoc('Contact', tn);
}
//========================= Overloaded query for link batch_no =============================================================
cur_frm.fields_dict['delivery_note_details'].grid.get_field('batch_no').get_query= function(doc, cdt, cdn) {
var d = locals[cdt][cdn];
if(d.item_code){
return "SELECT tabBatch.name, tabBatch.description FROM tabBatch WHERE tabBatch.docstatus != 2 AND tabBatch.item = '"+ d.item_code +"' AND `tabBatch`.`name` like '%s' ORDER BY `tabBatch`.`name` DESC LIMIT 50"
}
else{
alert("Please enter Item Code.");
}
}
// ***************** Get project name *****************
cur_frm.fields_dict['project_name'].get_query = function(doc, cdt, cdn) {
var cond = '';
if(doc.customer) cond = '(`tabProject`.customer = "'+doc.customer+'" OR IFNULL(`tabProject`.customer,"")="") AND';
return repl('SELECT `tabProject`.name FROM `tabProject` WHERE `tabProject`.status = "Open" AND %(cond)s `tabProject`.name LIKE "%s" ORDER BY `tabProject`.name ASC LIMIT 50', {cond:cond});
}
/*
//---- get customer details ----------------------------
cur_frm.cscript.project_name = function(doc,cdt,cdn){
$c_obj(make_doclist(doc.doctype, doc.name),'pull_project_customer','', function(r,rt){
refresh_many(['customer','customer_name', 'customer_address', 'contact_person', 'territory', 'contact_no', 'email_id', 'customer_group']);
});
}
*/
// UTILITY FUNCTIONS
// ================================================================================================
/*
var cfn_set_fields = function(doc, cdt, cdn) {
var supplier_field_list = ['Supplier','supplier','supplier_address'];
var customer_field_list = ['Customer','customer','customer_name','customer_address','territory','customer_group','Business Associate','sales_partner','commission_rate','total_commission','sales_order_no','Get Items'];
if (doc.delivery_type == 'Rejected' && doc.purchase_receipt_no) {
unhide_field('purchase_receipt_no');
unhide_field(supplier_field_list);
hide_field(customer_field_list);
get_field(doc.doctype, 'delivery_type' , doc.name).permlevel = 1;
}
else if (doc.delivery_type == 'Subcontract' && doc.purchase_order_no) {
unhide_field('purchase_order_no');
unhide_field(supplier_field_list);
hide_field(cutomer_field_list);
get_field(doc.doctype, 'delivery_type' , doc.name).permlevel = 1;
}
else if (doc.delivery_type == 'Sample') unhide_field('to_warehouse');
else get_field(doc.doctype, 'delivery_type' , doc.name).permlevel = 0;
}
*/
// DOCTYPE TRIGGERS
// ================================================================================================
/*
// ***************** Get Contact Person based on customer selected *****************
cur_frm.fields_dict['contact_person'].get_query = function(doc, cdt, cdn) {
return 'SELECT `tabContact`.contact_name FROM `tabContact` WHERE ((`tabContact`.is_customer = 1 AND `tabContact`.customer = "'+ doc.customer+'") or (`tabContact`.is_sales_partner = 1 AND `tabContact`.sales_partner = "'+ doc.sales_partner+'")) AND `tabContact`.docstatus != 2 AND `tabContact`.contact_name LIKE "%s" ORDER BY `tabContact`.contact_name ASC LIMIT 50';
}
*/
/*
// ***************** get shipping address based on customer selected *****************
cur_frm.fields_dict['ship_det_no'].get_query = function(doc, cdt, cdn) {
return 'SELECT `tabShipping Address`.`name`, `tabShipping Address`.`ship_to`, `tabShipping Address`.`shipping_address` FROM `tabShipping Address` WHERE `tabShipping Address`.customer = "'+ doc.customer+'" AND `tabShipping Address`.`docstatus` != 2 AND `tabShipping Address`.`name` LIKE "%s" ORDER BY `tabShipping Address`.name ASC LIMIT 50';
}
*/
// *************** Customized link query for SALES ORDER based on customer and currency*****************************
cur_frm.fields_dict['sales_order_no'].get_query = function(doc) {
doc = locals[this.doctype][this.docname];
var cond = '';
if(doc.customer) {
if(doc.currency) cond = '`tabSales Order`.customer = "'+doc.customer+'" and `tabSales Order`.currency = "'+doc.currency+'" and';
else cond = '`tabSales Order`.customer = "'+doc.customer+'" and';
}
else {
if(doc.currency) cond = '`tabSales Order`.currency = "'+doc.currency+'" and';
else cond = '';
}
if(doc.project_name){
cond += '`tabSales Order`.project_name ="'+doc.project_name+'"';
}
return repl('SELECT DISTINCT `tabSales Order`.`name` FROM `tabSales Order` WHERE `tabSales Order`.company = "%(company)s" and `tabSales Order`.`docstatus` = 1 and `tabSales Order`.`status` != "Stopped" and ifnull(`tabSales Order`.per_delivered,0) < 100 and %(cond)s `tabSales Order`.%(key)s LIKE "%s" ORDER BY `tabSales Order`.`name` DESC LIMIT 50', {company:doc.company,cond:cond})
}
// ****************************** DELIVERY TYPE ************************************
cur_frm.cscript.delivery_type = function(doc, cdt, cdn) {
if (doc.delivery_type = 'Sample') cfn_set_fields(doc, cdt, cdn);
}
cur_frm.cscript.serial_no = function(doc, cdt , cdn) {
var d = locals[cdt][cdn];
if (d.serial_no) {
get_server_fields('get_serial_details',d.serial_no,'delivery_note_details',doc,cdt,cdn,1);
}
}
/*
// this won't work in case of Sales Bom item where item.is_stock_item = 'No'
cur_frm.fields_dict['delivery_note_details'].grid.get_field('warehouse').get_query= function(doc, cdt, cdn) {
var d = locals[cdt][cdn];
return "SELECT `tabBin`.`warehouse`, `tabBin`.`actual_qty` FROM `tabBin` WHERE `tabBin`.`item_code` = '"+ d.item_code +"' AND ifnull(`tabBin`.`actual_qty`,0) > 0 AND `tabBin`.`warehouse` like '%s' ORDER BY `tabBin`.`warehouse` DESC LIMIT 50";
}
*/
cur_frm.cscript.warehouse = function(doc, cdt, cdn) {
var d = locals[cdt][cdn];
if (! d.item_code) {alert("please enter item code first"); return};
if (d.warehouse) {
arg = "{'item_code':'" + d.item_code + "','warehouse':'" + d.warehouse +"'}";
get_server_fields('get_actual_qty',arg,'delivery_note_details',doc,cdt,cdn,1);
}
}
cur_frm.fields_dict['transporter_name'].get_query = function(doc) {
return 'SELECT DISTINCT `tabSupplier`.`name` FROM `tabSupplier` WHERE `tabSupplier`.supplier_type = "transporter" AND `tabSupplier`.docstatus != 2 AND `tabSupplier`.%(key)s LIKE "%s" ORDER BY `tabSupplier`.`name` LIMIT 50';
}
//-----------------------------------Make Sales Invoice----------------------------------------------
cur_frm.cscript['Make Sales Invoice'] = function() {
var doc = cur_frm.doc
n = createLocal('Receivable Voucher');
$c('dt_map', args={
'docs':compress_doclist([locals['Receivable Voucher'][n]]),
'from_doctype':doc.doctype,
'to_doctype':'Receivable Voucher',
'from_docname':doc.name,
'from_to_list':"[['Delivery Note','Receivable Voucher'],['Delivery Note Detail','RV Detail'],['RV Tax Detail','RV Tax Detail'],['Sales Team','Sales Team']]"
}, function(r,rt) {
loaddoc('Receivable Voucher', n);
}
);
}
//-----------------------------------Make Installation Note----------------------------------------------
cur_frm.cscript['Make Installation Note'] = function() {
var doc = cur_frm.doc;
if(doc.per_installed < 100){
n = createLocal('Installation Note');
$c('dt_map', args={
'docs':compress_doclist([locals['Installation Note'][n]]),
'from_doctype':doc.doctype,
'to_doctype':'Installation Note',
'from_docname':doc.name,
'from_to_list':"[['Delivery Note','Installation Note'],['Delivery Note Detail','Installed Item Details']]"
}, function(r,rt) {
loaddoc('Installation Note', n);
}
);
}
else if(doc.per_installed >= 100)
msgprint("Item installation is already completed")
}
//get query select Territory
//=======================================================================================================================
cur_frm.fields_dict['territory'].get_query = function(doc,cdt,cdn) {
return 'SELECT `tabTerritory`.`name`,`tabTerritory`.`parent_territory` FROM `tabTerritory` WHERE `tabTerritory`.`is_group` = "No" AND `tabTerritory`.`docstatus`!= 2 AND `tabTerritory`.%(key)s LIKE "%s" ORDER BY `tabTerritory`.`name` ASC LIMIT 50';
}
//------------------------for printing without amount----------
var set_print_hide= function(doc, cdt, cdn){
if (doc.print_without_amount) {
fields['Delivery Note']['currency'].print_hide = 1;
fields['Delivery Note Detail']['export_rate'].print_hide = 1;
fields['Delivery Note Detail']['adj_rate'].print_hide = 1;
fields['Delivery Note Detail']['ref_rate'].print_hide = 1;
fields['Delivery Note Detail']['export_amount'].print_hide = 1;
} else {
fields['Delivery Note']['currency'].print_hide = 0;
fields['Delivery Note Detail']['export_rate'].print_hide = 0;
fields['Delivery Note Detail']['adj_rate'].print_hide = 0;
fields['Delivery Note Detail']['ref_rate'].print_hide = 0;
fields['Delivery Note Detail']['export_amount'].print_hide = 0;
}
}
cur_frm.cscript.print_without_amount = function(doc, cdt, cdn) {
set_print_hide(doc, cdt, cdn);
}
//****************** For print sales order no and date*************************
cur_frm.pformat.sales_order_no= function(doc, cdt, cdn){
//function to make row of table
var make_row = function(title,val1, val2, bold){
var bstart = '<b>'; var bend = '</b>';
return '<tr><td style="width:39%;">'+(bold?bstart:'')+title+(bold?bend:'')+'</td>'
+'<td style="width:61%;text-align:left;">'+val1+(val2?' ('+dateutil.str_to_user(val2)+')':'')+'</td>'
+'</tr>'
}
out ='';
var cl = getchildren('Delivery Note Detail',doc.name,'delivery_note_details');
// outer table
var out='<div><table class="noborder" style="width:100%"><tr><td style="width: 50%"></td><td>';
// main table
out +='<table class="noborder" style="width:100%">';
// add rows
if(cl.length){
prevdoc_list = new Array();
for(var i=0;i<cl.length;i++){
if(cl[i].prevdoc_doctype == 'Sales Order' && cl[i].prevdoc_docname && prevdoc_list.indexOf(cl[i].prevdoc_docname) == -1) {
prevdoc_list.push(cl[i].prevdoc_docname);
if(prevdoc_list.length ==1)
out += make_row(cl[i].prevdoc_doctype, cl[i].prevdoc_docname, cl[i].prevdoc_date,0);
else
out += make_row('', cl[i].prevdoc_docname, cl[i].prevdoc_date,0);
}
}
}
out +='</table></td></tr></table></div>';
return out;
}

View File

@@ -0,0 +1,442 @@
# Please edit this list and import only required elements
import webnotes
from webnotes.utils import add_days, add_months, add_years, cint, cstr, date_diff, default_fields, flt, fmt_money, formatdate, generate_hash, getTraceback, get_defaults, get_first_day, get_last_day, getdate, has_common, month_name, now, nowdate, replace_newlines, sendmail, set_default, str_esc_quote, user_format, validate_email_add
from webnotes.model import db_exists
from webnotes.model.doc import Document, addchild, removechild, getchildren, make_autoname, SuperDocType
from webnotes.model.doclist import getlist, copy_doclist
from webnotes.model.code import get_obj, get_server_obj, run_server_obj, updatedb, check_syntax
from webnotes import session, form, is_testing, msgprint, errprint
set = webnotes.conn.set
sql = webnotes.conn.sql
get_value = webnotes.conn.get_value
in_transaction = webnotes.conn.in_transaction
convert_to_lists = webnotes.conn.convert_to_lists
# -----------------------------------------------------------------------------------------
from utilities.transaction_base import TransactionBase
class DocType(TransactionBase):
def __init__(self, doc, doclist=[]):
self.doc = doc
self.doclist = doclist
self.tname = 'Delivery Note Detail'
self.fname = 'delivery_note_details'
# Notification objects
self.notify_obj = get_obj('Notification Control')
# Autoname
# ---------
def autoname(self):
self.doc.name = make_autoname(self.doc.naming_series+'.#####')
# DOCTYPE TRIGGERS FUNCTIONS
# ==============================================================================
#************Fiscal Year Validation*****************************
def validate_fiscal_year(self):
get_obj('Sales Common').validate_fiscal_year(self.doc.fiscal_year,self.doc.posting_date,'Posting Date')
# ******************* Get Customer Details ***********************
#def get_customer_details(self):
# sales_com_obj = get_obj('Sales Common')
# sales_com_obj.get_customer_details(self)
# sales_com_obj.get_shipping_details(self)
# ****** Get contact person details based on customer selected ****
def get_contact_details(self):
return cstr(get_obj('Sales Common').get_contact_details(self,0))
# *********** Get Commission rate of Sales Partner ****************
def get_comm_rate(self, sales_partner):
return get_obj('Sales Common').get_comm_rate(sales_partner, self)
# *************** Pull Sales Order Details ************************
def pull_sales_order_details(self):
self.validate_prev_docname()
self.doc.clear_table(self.doclist,'other_charges')
if self.doc.sales_order_no:
get_obj('DocType Mapper', 'Sales Order-Delivery Note').dt_map('Sales Order', 'Delivery Note', self.doc.sales_order_no, self.doc, self.doclist, "[['Sales Order', 'Delivery Note'],['Sales Order Detail', 'Delivery Note Detail'],['RV Tax Detail','RV Tax Detail'],['Sales Team','Sales Team']]")
else:
msgprint("Please select Sales Order No. whose details need to be pulled")
return cstr(self.doc.sales_order_no)
#-------------------set item details -uom and item group----------------
def set_item_details(self):
for d in getlist(self.doclist,'delivery_note_details'):
res = sql("select stock_uom, item_group from `tabItem` where name ='%s'"%d.item_code)
if not d.stock_uom: d.stock_uom = res and cstr(res[0][0]) or ''
if not d.item_group: d.item_group = res and cstr(res[0][1]) or ''
d.save()
# ::::: Validates that Sales Order is not pulled twice :::::::
def validate_prev_docname(self):
for d in getlist(self.doclist, 'delivery_note_details'):
if self.doc.sales_order_no == d.prevdoc_docname:
msgprint(cstr(self.doc.sales_order_no) + " sales order details have already been pulled. ")
raise Exception, "Validation Error. "
#Set Actual Qty based on item code and warehouse
#------------------------------------------------------
def set_actual_qty(self):
for d in getlist(self.doclist, 'delivery_note_details'):
if d.item_code and d.warehouse:
actual_qty = sql("select actual_qty from `tabBin` where item_code = '%s' and warehouse = '%s'" % (d.item_code, d.warehouse))
d.actual_qty = actual_qty and flt(actual_qty[0][0]) or 0
# GET TERMS & CONDITIONS
# -------------------------------------
def get_tc_details(self):
return get_obj('Sales Common').get_tc_details(self)
#pull project customer
#-------------------------
def pull_project_customer(self):
res = sql("select customer from `tabProject` where name = '%s'"%self.doc.project_name)
if res:
get_obj('DocType Mapper', 'Project-Delivery Note').dt_map('Project', 'Delivery Note', self.doc.project_name, self.doc, self.doclist, "[['Project', 'Delivery Note']]")
# DELIVERY NOTE DETAILS TRIGGER FUNCTIONS
# ================================================================================
# ***************** Get Item Details ******************************
def get_item_details(self, item_code):
return get_obj('Sales Common').get_item_details(item_code, self)
# *** Re-calculates Basic Rate & amount based on Price List Selected ***
def get_adj_percent(self, arg=''):
get_obj('Sales Common').get_adj_percent(self)
# ********** Get Actual Qty of item in warehouse selected *************
def get_actual_qty(self,args):
args = eval(args)
actual_qty = sql("select actual_qty from `tabBin` where item_code = '%s' and warehouse = '%s'" % (args['item_code'], args['warehouse']), as_dict=1)
ret = {
'actual_qty' : actual_qty and flt(actual_qty[0]['actual_qty']) or 0
}
return cstr(ret)
# OTHER CHARGES TRIGGER FUNCTIONS
# ====================================================================================
# *********** Get Tax rate if account type is TAX ********************
def get_rate(self,arg):
return get_obj('Sales Common').get_rate(arg)
# Load Default Charges
# ----------------------------------------------------------
def load_default_taxes(self):
return get_obj('Sales Common').load_default_taxes(self)
# **** Pull details from other charges master (Get Other Charges) ****
def get_other_charges(self):
return get_obj('Sales Common').get_other_charges(self)
#check in manage account if sales order required or not.
# ====================================================================================
def so_required(self):
res = sql("select value from `tabSingles` where doctype = 'Manage Account' and field = 'so_required'")
if res and res[0][0] == 'Yes':
for d in getlist(self.doclist,'delivery_note_details'):
if not d.prevdoc_docname:
msgprint("Sales Order No. required against item %s"%d.item_code)
raise Exception
# VALIDATE
# ====================================================================================
def validate(self):
self.so_required()
self.validate_fiscal_year()
self.validate_proj_cust()
sales_com_obj = get_obj(dt = 'Sales Common')
sales_com_obj.check_stop_sales_order(self)
sales_com_obj.check_active_sales_items(self)
sales_com_obj.get_prevdoc_date(self)
self.validate_mandatory()
#self.validate_prevdoc_details()
self.validate_reference_value()
self.validate_for_items()
sales_com_obj.make_packing_list(self,'delivery_note_details')
get_obj('Stock Ledger').validate_serial_no(self, 'packing_details')
sales_com_obj.validate_max_discount(self, 'delivery_note_details') #verify whether rate is not greater than max discount
sales_com_obj.get_allocated_sum(self) # this is to verify that the allocated % of sales persons is 100%
sales_com_obj.check_conversion_rate(self)
# ::::::: Get total in Words ::::::::
self.doc.in_words = sales_com_obj.get_total_in_words(get_defaults()['currency'], self.doc.rounded_total)
self.doc.in_words_export = sales_com_obj.get_total_in_words(self.doc.currency, self.doc.rounded_total_export)
# ::::::: Set actual qty for each item in selected warehouse :::::::
self.update_current_stock()
# :::::: set DN status :::::::
self.doc.status = 'Draft'
if not self.doc.billing_status: self.doc.billing_status = 'Not Billed'
if not self.doc.installation_status: self.doc.installation_status = 'Not Installed'
# ************** Validate Mandatory *************************
def validate_mandatory(self):
# :::::::::: Amendment Date ::::::::::::::
if self.doc.amended_from and not self.doc.amendment_date:
msgprint("Please Enter Amendment Date")
raise Exception, "Validation Error. "
#check for does customer belong to same project as entered..
#-------------------------------------------------------------------------------------------------
def validate_proj_cust(self):
if self.doc.project_name and self.doc.customer:
res = sql("select name from `tabProject` where name = '%s' and (customer = '%s' or ifnull(customer,'')='')"%(self.doc.project_name, self.doc.customer))
if not res:
msgprint("Customer - %s does not belong to project - %s. \n\nIf you want to use project for multiple customers then please make customer details blank in project - %s."%(self.doc.customer,self.doc.project_name,self.doc.project_name))
raise Exception
# Validate values with reference document
#----------------------------------------
def validate_reference_value(self):
get_obj('DocType Mapper', 'Sales Order-Delivery Note', with_children = 1).validate_reference_value(self, self.doc.name)
# ******* Validate Previous Document Details ************
def validate_prevdoc_details(self):
for d in getlist(self.doclist,'delivery_note_details'):
prevdoc = d.prevdoc_doctype
prevdoc_docname = d.prevdoc_docname
if prevdoc_docname and prevdoc:
# ::::::::::: Validates Transaction Date of DN and previous doc (i.e. SO , PO, PR) *********
trans_date = sql("select transaction_date from `tab%s` where name = '%s'" %(prevdoc,prevdoc_docname))[0][0]
if trans_date and getdate(self.doc.transaction_date) < (trans_date):
msgprint("Your Voucher Date cannot be before "+cstr(prevdoc)+" Date.")
raise Exception
# ::::::::: Validates DN and previous doc details ::::::::::::::::::
get_name = sql("select name from `tab%s` where name = '%s'" % (prevdoc, prevdoc_docname))
name = get_name and get_name[0][0] or ''
if name: #check for incorrect docname
if prevdoc == 'Sales Order':
dt = sql("select company, docstatus, customer, currency, sales_partner from `tab%s` where name = '%s'" % (prevdoc, name))
cust_name = dt and dt[0][2] or ''
if cust_name != self.doc.customer:
msgprint(cstr(prevdoc) + ": " + cstr(prevdoc_docname) + " customer :" + cstr(cust_name) + " does not match with customer : " + cstr(self.doc.customer) + " of current document.")
raise Exception, "Validation Error. "
sal_partner = dt and dt[0][4] or ''
if sal_partner != self.doc.sales_partner:
msgprint(cstr(prevdoc) + ": " + cstr(prevdoc_docname) + " sales partner name :" + cstr(sal_partner) + " does not match with sales partner name : " + cstr(self.doc.sales_partner_name) + " of current document.")
raise Exception, "Validation Error. "
else:
dt = sql("select company, docstatus, supplier, currency from `tab%s` where name = '%s'" % (prevdoc, name))
supp_name = dt and dt[0][2] or ''
company_name = dt and dt[0][0] or ''
docstatus = dt and dt[0][1] or 0
currency = dt and dt[0][3] or ''
if (currency != self.doc.currency):
msgprint(cstr(prevdoc) + ": " + cstr(prevdoc_docname) + " currency : "+ cstr(currency) + "does not match with Currency: " + cstr(self.doc.currency) + "of current document")
raise Exception, "Validation Error."
if (company_name != self.doc.company):
msgprint(cstr(prevdoc) + ": " + cstr(prevdoc_docname) + " does not belong to the Company: " + cstr(self.doc.company_name))
raise Exception, "Validation Error."
if (docstatus != 1):
msgprint(cstr(prevdoc) + ": " + cstr(prevdoc_docname) + " is not Submitted Document.")
raise Exception, "Validation Error."
else:
msgprint(cstr(prevdoc) + ": " + cstr(prevdoc_docname) + " is not a valid " + cstr(prevdoc))
raise Exception, "Validation Error."
# ******************** Validate Items **************************
def validate_for_items(self):
check_list, chk_dupl_itm = [], []
for d in getlist(self.doclist,'delivery_note_details'):
ch = sql("select is_stock_item from `tabItem` where name = '%s'"%d.item_code)
if d.prevdoc_doctype and d.prevdoc_detail_docname and ch and ch[0][0]=='Yes':
self.validate_items_with_prevdoc(d)
# validates whether item is not entered twice
e = [d.item_code, d.description, d.warehouse, d.prevdoc_docname or '', d.batch_no or '']
f = [d.item_code, d.description, d.prevdoc_docname or '']
if ch and ch[0][0] == 'Yes':
if e in check_list:
msgprint("Please check whether item %s has been entered twice wrongly." % d.item_code)
else:
check_list.append(e)
elif ch and ch[0][0] == 'No':
if f in chk_dupl_itm:
msgprint("Please check whether item %s has been entered twice wrongly." % d.item_code)
else:
chk_dupl_itm.append(f)
# check if same item, warehouse present in prevdoc
# ------------------------------------------------------------------
def validate_items_with_prevdoc(self, d):
if d.prevdoc_doctype == 'Sales Order':
data = sql("select item_code, reserved_warehouse from `tabSales Order Detail` where parent = '%s' and name = '%s'" % (d.prevdoc_docname, d.prevdoc_detail_docname))
if d.prevdoc_doctype == 'Purchase Receipt':
data = sql("select item_code, rejected_warehouse from `tabPurchase Receipt Detail` where parent = '%s' and name = '%s'" % (d.prevdoc_docname, d.prevdoc_detail_docname))
if not data or data[0][0] != d.item_code or data[0][1] != d.warehouse:
msgprint("Item: %s / Warehouse: %s is not matching with Sales Order: %s. Sales Order might be modified after fetching data from it. Please delete items and fetch again." % (d.item_code, d.warehouse, d.prevdoc_docname))
raise Exception
# ********* UPDATE CURRENT STOCK *****************************
def update_current_stock(self):
for d in getlist(self.doclist, 'delivery_note_details'):
bin = sql("select actual_qty from `tabBin` where item_code = %s and warehouse = %s", (d.item_code, d.warehouse), as_dict = 1)
d.actual_qty = bin and flt(bin[0]['actual_qty']) or 0
for d in getlist(self.doclist, 'packing_details'):
bin = sql("select actual_qty, projected_qty from `tabBin` where item_code = %s and warehouse = %s", (d.item_code, d.warehouse), as_dict = 1)
d.actual_qty = bin and flt(bin[0]['actual_qty']) or 0
d.projected_qty = bin and flt(bin[0]['projected_qty']) or 0
# ON SUBMIT
# =================================================================================================
def on_submit(self):
set(self.doc, 'message', 'Items against your Order #%s have been delivered. Delivery #%s: ' % (self.doc.po_no, self.doc.name))
self.check_qty_in_stock()
# Check for Approving Authority
get_obj('Authorization Control').validate_approving_authority(self.doc.doctype, self.doc.company, self.doc.grand_total, self)
sl_obj = get_obj("Stock Ledger")
sl_obj.validate_serial_no_warehouse(self, 'packing_details')
sl_obj.update_serial_record(self, 'packing_details', is_submit = 1, is_incoming = 0)
get_obj("Sales Common").update_prevdoc_detail(1,self)
self.update_stock_ledger(update_stock = 1)
#------------Check Credit Limit---------------------
self.credit_limit()
# set DN status
set(self.doc, 'status', 'Submitted')
# on submit notification
self.notify_obj.notify_contact('Delivery Note',self.doc.doctype,self.doc.name, self.doc.email_id, self.doc.contact_person)
# *********** Checks whether actual quantity is present in warehouse *************
def check_qty_in_stock(self):
for d in getlist(self.doclist, 'packing_details'):
is_stock_item = sql("select is_stock_item from `tabItem` where name = '%s'" % d.item_code)[0][0]
if is_stock_item == 'Yes' and d.warehouse and flt(d.qty) > flt(d.actual_qty):
msgprint("For Item: " + cstr(d.item_code) + " at Warehouse: " + cstr(d.warehouse) + " Quantity: " + cstr(d.qty) +" is not Available. (Must be less than or equal to " + cstr(d.actual_qty) + " )")
raise Exception, "Validation Error"
# ON CANCEL
# =================================================================================================
def on_cancel(self):
sales_com_obj = get_obj(dt = 'Sales Common')
sales_com_obj.check_stop_sales_order(self)
self.check_next_docstatus()
get_obj('Stock Ledger').update_serial_record(self, 'packing_details', is_submit = 0, is_incoming = 0)
sales_com_obj.update_prevdoc_detail(0,self)
self.update_stock_ledger(update_stock = -1)
# :::::: set DN status :::::::
set(self.doc, 'status', 'Cancelled')
# ******************** Check Next DocStatus **************************
def check_next_docstatus(self):
submit_rv = sql("select t1.name from `tabReceivable Voucher` t1,`tabRV Detail` t2 where t1.name = t2.parent and t2.delivery_note = '%s' and t1.docstatus = 1" % (self.doc.name))
if submit_rv:
msgprint("Sales Invoice : " + cstr(submit_rv[0][0]) + " has already been submitted !")
raise Exception , "Validation Error."
submit_in = sql("select t1.name from `tabInstallation Note` t1, `tabInstalled Item Details` t2 where t1.name = t2.parent and t2.prevdoc_docname = '%s' and t1.docstatus = 1" % (self.doc.name))
if submit_in:
msgprint("Installation Note : "+cstr(submit_in[0][0]) +" has already been submitted !")
raise Exception , "Validation Error."
# UPDATE STOCK LEDGER
# =================================================================================================
def update_stock_ledger(self, update_stock, is_stopped = 0):
self.values = []
for d in self.get_item_list(is_stopped):
stock_item = sql("SELECT is_stock_item, is_sample_item FROM tabItem where name = '%s'"%(d[1]), as_dict = 1) # stock ledger will be updated only if it is a stock item
if stock_item[0]['is_stock_item'] == "Yes":
if not d[0]:
msgprint("Message: Please enter Warehouse for item %s as it is stock item."% d[1])
raise Exception
# if prevdoc_doctype = "Sales Order"
if d[3] < 0 :
# Reduce Reserved Qty from warehouse
bin = get_obj('Warehouse', d[0]).update_bin(0, flt(update_stock) * flt(d[3]), 0, 0, 0, d[1], self.doc.transaction_date)
# Reduce actual qty from warehouse
self.make_sl_entry(d, d[0], - flt(d[2]) , 0, update_stock)
get_obj('Stock Ledger', 'Stock Ledger').update_stock(self.values)
# ***************** Gets Items from packing list *****************
def get_item_list(self, is_stopped):
return get_obj('Sales Common').get_item_list(self, is_stopped)
# ********************** Make Stock Entry ************************************
def make_sl_entry(self, d, wh, qty, in_value, update_stock):
self.values.append({
'item_code' : d[1],
'warehouse' : wh,
'transaction_date' : self.doc.transaction_date,
'posting_date' : self.doc.posting_date,
'posting_time' : self.doc.posting_time,
'voucher_type' : 'Delivery Note',
'voucher_no' : self.doc.name,
'voucher_detail_no' : '',
'actual_qty' : qty,
'stock_uom' : d[4],
'incoming_rate' : in_value,
'company' : self.doc.company,
'fiscal_year' : self.doc.fiscal_year,
'is_cancelled' : (update_stock==1) and 'No' or 'Yes',
'batch_no' : d[5],
'serial_no' : d[6]
})
# SEND SMS
# ============================================================================================
def send_sms(self):
if not self.doc.customer_mobile_no:
msgprint("Please enter customer mobile no")
elif not self.doc.message:
msgprint("Please enter the message you want to send")
else:
msgprint(get_obj("SMS Control", "SMS Control").send_sms([self.doc.customer_mobile_no,], self.doc.message))
#------------ check credit limit of items in DN Detail which are not fetched from sales order----------
def credit_limit(self):
amount, total = 0, 0
for d in getlist(self.doclist, 'delivery_note_details'):
if not d.prevdoc_docname:
amount += d.amount
if amount != 0:
total = (amount/self.doc.net_total)*self.doc.grand_total
get_obj('Sales Common').check_credit(self, total)
# on update
def on_update(self):
self.set_actual_qty()
get_obj('Stock Ledger').scrub_serial_nos(self)
# Repair Delivery Note
# ===========================================
def repair_delivery_note(self):
get_obj('Sales Common', 'Sales Common').repair_curr_doctype_details(self)

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,687 @@
[
{
'_last_update': None,
'_user_tags': None,
'allow_attach': None,
'allow_copy': None,
'allow_email': None,
'allow_print': None,
'allow_rename': None,
'allow_trash': None,
'autoname': None,
'change_log': None,
'client_script': None,
'client_script_core': None,
'client_string': None,
'colour': 'White:FFF',
'creation': '2010-08-08 17:08:58',
'description': None,
'docstatus': 0,
'doctype': 'DocType',
'document_type': None,
'dt_template': None,
'hide_heading': None,
'hide_toolbar': None,
'idx': None,
'in_create': None,
'in_dialog': None,
'is_transaction_doc': None,
'issingle': None,
'istable': 1,
'max_attachments': None,
'menu_index': None,
'modified': '2011-03-14 14:50:55',
'modified_by': 'Administrator',
'module': 'Material Management',
'name': 'Delivery Note Packing Detail',
'name_case': None,
'owner': 'Administrator',
'parent': None,
'parent_node': None,
'parentfield': None,
'parenttype': None,
'print_outline': None,
'read_only': None,
'read_only_onload': None,
'search_fields': None,
'section_style': 'Tray',
'server_code': None,
'server_code_compiled': None,
'server_code_core': None,
'server_code_error': ' ',
'show_in_menu': 0,
'smallicon': None,
'use_template': None,
'version': 17
},
{
'allow_on_submit': None,
'colour': None,
'creation': '2010-08-08 17:08:58',
'default': None,
'depends_on': None,
'description': None,
'docstatus': 0,
'doctype': 'DocField',
'fieldname': 'parent_item',
'fieldtype': 'Link',
'hidden': None,
'icon': None,
'idx': 1,
'in_filter': None,
'label': 'Parent Item',
'modified': '2011-05-09 11:04:35',
'modified_by': 'Administrator',
'name': 'FL01028',
'no_copy': None,
'oldfieldname': 'parent_item',
'oldfieldtype': 'Link',
'options': 'Item',
'owner': 'Administrator',
'parent': 'Delivery Note Packing Detail',
'parentfield': 'fields',
'parenttype': 'DocType',
'permlevel': 1,
'print_hide': None,
'report_hide': None,
'reqd': None,
'search_index': None,
'trigger': None,
'width': None
},
{
'allow_on_submit': None,
'colour': 'White:FFF',
'creation': '2010-08-08 17:08:58',
'default': None,
'depends_on': None,
'description': None,
'docstatus': 0,
'doctype': 'DocField',
'fieldname': 'item_code',
'fieldtype': 'Link',
'hidden': None,
'icon': None,
'idx': 2,
'in_filter': 1,
'label': 'Item Code',
'modified': '2011-05-09 11:04:35',
'modified_by': 'Administrator',
'name': 'FL01029',
'no_copy': None,
'oldfieldname': 'item_code',
'oldfieldtype': 'Link',
'options': 'Item',
'owner': 'Administrator',
'parent': 'Delivery Note Packing Detail',
'parentfield': 'fields',
'parenttype': 'DocType',
'permlevel': 1,
'print_hide': None,
'report_hide': None,
'reqd': None,
'search_index': None,
'trigger': None,
'width': None
},
{
'allow_on_submit': None,
'colour': None,
'creation': '2010-09-01 15:47:53',
'default': None,
'depends_on': None,
'description': None,
'docstatus': 0,
'doctype': 'DocField',
'fieldname': 'item_name',
'fieldtype': 'Data',
'hidden': None,
'icon': None,
'idx': 3,
'in_filter': 1,
'label': 'Item Name',
'modified': '2011-05-09 11:04:35',
'modified_by': 'Administrator',
'name': 'FL03784',
'no_copy': None,
'oldfieldname': 'item_name',
'oldfieldtype': 'Data',
'options': None,
'owner': 'ashwini@webnotestech.com',
'parent': 'Delivery Note Packing Detail',
'parentfield': 'fields',
'parenttype': 'DocType',
'permlevel': 1,
'print_hide': None,
'report_hide': None,
'reqd': None,
'search_index': None,
'trigger': None,
'width': None
},
{
'allow_on_submit': None,
'colour': None,
'creation': '2010-08-08 17:08:58',
'default': None,
'depends_on': None,
'description': None,
'docstatus': 0,
'doctype': 'DocField',
'fieldname': 'parent_detail_docname',
'fieldtype': 'Data',
'hidden': 1,
'icon': None,
'idx': 4,
'in_filter': None,
'label': 'Parent Detail docname',
'modified': '2011-05-09 11:04:35',
'modified_by': 'Administrator',
'name': 'FL01030',
'no_copy': 1,
'oldfieldname': 'parent_detail_docname',
'oldfieldtype': 'Data',
'options': None,
'owner': 'jai@webnotestech.com',
'parent': 'Delivery Note Packing Detail',
'parentfield': 'fields',
'parenttype': 'DocType',
'permlevel': 1,
'print_hide': 1,
'report_hide': None,
'reqd': None,
'search_index': None,
'trigger': None,
'width': None
},
{
'allow_on_submit': None,
'colour': None,
'creation': '2010-08-08 17:08:58',
'default': None,
'depends_on': None,
'description': None,
'docstatus': 0,
'doctype': 'DocField',
'fieldname': 'description',
'fieldtype': 'Text',
'hidden': None,
'icon': None,
'idx': 5,
'in_filter': None,
'label': 'Description',
'modified': '2011-05-09 11:04:35',
'modified_by': 'Administrator',
'name': 'FL01031',
'no_copy': None,
'oldfieldname': 'description',
'oldfieldtype': 'Text',
'options': None,
'owner': 'Administrator',
'parent': 'Delivery Note Packing Detail',
'parentfield': 'fields',
'parenttype': 'DocType',
'permlevel': 1,
'print_hide': None,
'report_hide': None,
'reqd': None,
'search_index': None,
'trigger': None,
'width': '300px'
},
{
'allow_on_submit': None,
'colour': None,
'creation': '2010-08-08 17:08:58',
'default': None,
'depends_on': None,
'description': None,
'docstatus': 0,
'doctype': 'DocField',
'fieldname': 'warehouse',
'fieldtype': 'Link',
'hidden': None,
'icon': None,
'idx': 6,
'in_filter': None,
'label': 'Warehouse',
'modified': '2011-05-09 11:04:35',
'modified_by': 'Administrator',
'name': 'FL01034',
'no_copy': None,
'oldfieldname': 'warehouse',
'oldfieldtype': 'Link',
'options': 'Warehouse',
'owner': 'Administrator',
'parent': 'Delivery Note Packing Detail',
'parentfield': 'fields',
'parenttype': 'DocType',
'permlevel': 1,
'print_hide': None,
'report_hide': None,
'reqd': None,
'search_index': None,
'trigger': None,
'width': None
},
{
'allow_on_submit': None,
'colour': None,
'creation': '2010-08-08 17:08:58',
'default': None,
'depends_on': None,
'description': None,
'docstatus': 0,
'doctype': 'DocField',
'fieldname': 'qty',
'fieldtype': 'Currency',
'hidden': None,
'icon': None,
'idx': 7,
'in_filter': None,
'label': 'Qty',
'modified': '2011-05-09 11:04:35',
'modified_by': 'Administrator',
'name': 'FL01032',
'no_copy': None,
'oldfieldname': 'qty',
'oldfieldtype': 'Currency',
'options': None,
'owner': 'Administrator',
'parent': 'Delivery Note Packing Detail',
'parentfield': 'fields',
'parenttype': 'DocType',
'permlevel': 1,
'print_hide': None,
'report_hide': None,
'reqd': None,
'search_index': None,
'trigger': None,
'width': None
},
{
'allow_on_submit': None,
'colour': None,
'creation': '2011-05-09 11:04:35',
'default': None,
'depends_on': None,
'description': None,
'docstatus': 0,
'doctype': 'DocField',
'fieldname': 'serial_no',
'fieldtype': 'Text',
'hidden': None,
'icon': None,
'idx': 8,
'in_filter': None,
'label': 'Serial No',
'modified': '2011-05-09 11:04:35',
'modified_by': 'Administrator',
'name': '000000471',
'no_copy': None,
'oldfieldname': None,
'oldfieldtype': None,
'options': None,
'owner': 'Administrator',
'parent': 'Delivery Note Packing Detail',
'parentfield': 'fields',
'parenttype': 'DocType',
'permlevel': 0,
'print_hide': None,
'report_hide': None,
'reqd': None,
'search_index': None,
'trigger': None,
'width': None
},
{
'allow_on_submit': None,
'colour': None,
'creation': '2010-08-08 17:08:58',
'default': None,
'depends_on': None,
'description': None,
'docstatus': 0,
'doctype': 'DocField',
'fieldname': 'actual_qty',
'fieldtype': 'Currency',
'hidden': None,
'icon': None,
'idx': 9,
'in_filter': None,
'label': 'Actual Qty',
'modified': '2011-05-09 11:04:35',
'modified_by': 'Administrator',
'name': 'FL01035',
'no_copy': 1,
'oldfieldname': 'actual_qty',
'oldfieldtype': 'Currency',
'options': None,
'owner': 'Administrator',
'parent': 'Delivery Note Packing Detail',
'parentfield': 'fields',
'parenttype': 'DocType',
'permlevel': 1,
'print_hide': None,
'report_hide': None,
'reqd': None,
'search_index': None,
'trigger': None,
'width': None
},
{
'allow_on_submit': None,
'colour': None,
'creation': '2010-12-21 14:51:19',
'default': None,
'depends_on': None,
'description': None,
'docstatus': 0,
'doctype': 'DocField',
'fieldname': 'projected_qty',
'fieldtype': 'Currency',
'hidden': None,
'icon': None,
'idx': 10,
'in_filter': None,
'label': 'Projected Qty',
'modified': '2011-05-09 11:04:35',
'modified_by': 'Administrator',
'name': 'FL04427',
'no_copy': 1,
'oldfieldname': 'projected_qty',
'oldfieldtype': 'Currency',
'options': None,
'owner': 'Administrator',
'parent': 'Delivery Note Packing Detail',
'parentfield': 'fields',
'parenttype': 'DocType',
'permlevel': 1,
'print_hide': None,
'report_hide': None,
'reqd': None,
'search_index': None,
'trigger': None,
'width': None
},
{
'allow_on_submit': None,
'colour': None,
'creation': '2010-08-08 17:08:58',
'default': None,
'depends_on': None,
'description': None,
'docstatus': 0,
'doctype': 'DocField',
'fieldname': 'uom',
'fieldtype': 'Link',
'hidden': None,
'icon': None,
'idx': 11,
'in_filter': None,
'label': 'UOM',
'modified': '2011-05-09 11:04:35',
'modified_by': 'Administrator',
'name': 'FL01033',
'no_copy': None,
'oldfieldname': 'uom',
'oldfieldtype': 'Link',
'options': 'UOM',
'owner': 'Administrator',
'parent': 'Delivery Note Packing Detail',
'parentfield': 'fields',
'parenttype': 'DocType',
'permlevel': 1,
'print_hide': None,
'report_hide': None,
'reqd': None,
'search_index': None,
'trigger': None,
'width': None
},
{
'allow_on_submit': None,
'colour': None,
'creation': '2010-08-08 17:08:58',
'default': None,
'depends_on': None,
'description': None,
'docstatus': 0,
'doctype': 'DocField',
'fieldname': 'planned_qty',
'fieldtype': 'Currency',
'hidden': 1,
'icon': None,
'idx': 12,
'in_filter': None,
'label': 'Planned Qty ',
'modified': '2011-05-09 11:04:35',
'modified_by': 'Administrator',
'name': 'FL01036',
'no_copy': 1,
'oldfieldname': 'planned_qty',
'oldfieldtype': 'Currency',
'options': None,
'owner': 'Administrator',
'parent': 'Delivery Note Packing Detail',
'parentfield': 'fields',
'parenttype': 'DocType',
'permlevel': 1,
'print_hide': 1,
'report_hide': None,
'reqd': None,
'search_index': None,
'trigger': None,
'width': None
},
{
'allow_on_submit': None,
'colour': None,
'creation': '2010-08-08 17:08:58',
'default': None,
'depends_on': None,
'description': None,
'docstatus': 0,
'doctype': 'DocField',
'fieldname': 'produced_qty',
'fieldtype': 'Currency',
'hidden': 1,
'icon': None,
'idx': 13,
'in_filter': None,
'label': 'Produced Qty',
'modified': '2011-05-09 11:04:35',
'modified_by': 'Administrator',
'name': 'FL01037',
'no_copy': 1,
'oldfieldname': 'produced_qty',
'oldfieldtype': 'Currency',
'options': None,
'owner': 'Administrator',
'parent': 'Delivery Note Packing Detail',
'parentfield': 'fields',
'parenttype': 'DocType',
'permlevel': 1,
'print_hide': 1,
'report_hide': None,
'reqd': None,
'search_index': None,
'trigger': None,
'width': None
},
{
'allow_on_submit': None,
'colour': 'White:FFF',
'creation': '2010-08-08 17:08:58',
'default': None,
'depends_on': None,
'description': None,
'docstatus': 0,
'doctype': 'DocField',
'fieldname': 'prevdoc_doctype',
'fieldtype': 'Data',
'hidden': 1,
'icon': None,
'idx': 14,
'in_filter': None,
'label': 'Prevdoc DocType',
'modified': '2011-05-09 11:04:35',
'modified_by': 'Administrator',
'name': 'FL01038',
'no_copy': None,
'oldfieldname': 'prevdoc_doctype',
'oldfieldtype': 'Data',
'options': None,
'owner': 'Administrator',
'parent': 'Delivery Note Packing Detail',
'parentfield': 'fields',
'parenttype': 'DocType',
'permlevel': 1,
'print_hide': 1,
'report_hide': None,
'reqd': None,
'search_index': None,
'trigger': None,
'width': None
},
{
'allow_on_submit': None,
'colour': None,
'creation': '2010-08-08 17:08:58',
'default': None,
'depends_on': None,
'description': 'The date at which current entry is made in system.',
'docstatus': 0,
'doctype': 'DocField',
'fieldname': 'transaction_date',
'fieldtype': 'Date',
'hidden': 0,
'icon': None,
'idx': 15,
'in_filter': None,
'label': 'Sales Order Date',
'modified': '2011-05-09 11:04:35',
'modified_by': 'Administrator',
'name': 'FL01039',
'no_copy': None,
'oldfieldname': 'transaction_date',
'oldfieldtype': 'Date',
'options': None,
'owner': 'Administrator',
'parent': 'Delivery Note Packing Detail',
'parentfield': 'fields',
'parenttype': 'DocType',
'permlevel': 1,
'print_hide': 1,
'report_hide': None,
'reqd': None,
'search_index': None,
'trigger': None,
'width': None
},
{
'allow_on_submit': None,
'colour': None,
'creation': '2010-08-08 17:08:58',
'default': None,
'depends_on': None,
'description': None,
'docstatus': 0,
'doctype': 'DocField',
'fieldname': 'delivery_date',
'fieldtype': 'Date',
'hidden': 0,
'icon': None,
'idx': 16,
'in_filter': None,
'label': 'Expected Delivery Date',
'modified': '2011-05-09 11:04:35',
'modified_by': 'Administrator',
'name': 'FL01040',
'no_copy': None,
'oldfieldname': 'delivery_date',
'oldfieldtype': 'Date',
'options': None,
'owner': 'Administrator',
'parent': 'Delivery Note Packing Detail',
'parentfield': 'fields',
'parenttype': 'DocType',
'permlevel': 1,
'print_hide': 1,
'report_hide': None,
'reqd': None,
'search_index': None,
'trigger': None,
'width': None
},
{
'allow_on_submit': None,
'colour': None,
'creation': '2010-08-08 17:08:58',
'default': None,
'depends_on': None,
'description': None,
'docstatus': 0,
'doctype': 'DocField',
'fieldname': 'confirmation_date',
'fieldtype': 'Date',
'hidden': 1,
'icon': None,
'idx': 17,
'in_filter': None,
'label': 'Confirmed delivery date',
'modified': '2011-05-09 11:04:35',
'modified_by': 'Administrator',
'name': 'FL01041',
'no_copy': 1,
'oldfieldname': 'confirmation_date',
'oldfieldtype': 'Date',
'options': None,
'owner': 'Administrator',
'parent': 'Delivery Note Packing Detail',
'parentfield': 'fields',
'parenttype': 'DocType',
'permlevel': 1,
'print_hide': 1,
'report_hide': None,
'reqd': None,
'search_index': None,
'trigger': None,
'width': None
},
{
'allow_on_submit': 1,
'colour': None,
'creation': '2010-08-08 17:08:58',
'default': None,
'depends_on': None,
'description': None,
'docstatus': 0,
'doctype': 'DocField',
'fieldname': 'page_break',
'fieldtype': 'Check',
'hidden': None,
'icon': None,
'idx': 18,
'in_filter': None,
'label': 'Page Break',
'modified': '2011-05-09 11:04:35',
'modified_by': 'Administrator',
'name': 'FL01042',
'no_copy': None,
'oldfieldname': 'page_break',
'oldfieldtype': 'Check',
'options': None,
'owner': 'Administrator',
'parent': 'Delivery Note Packing Detail',
'parentfield': 'fields',
'parenttype': 'DocType',
'permlevel': 1,
'print_hide': None,
'report_hide': None,
'reqd': None,
'search_index': None,
'trigger': None,
'width': None
}
]

View File

@@ -0,0 +1,87 @@
cur_frm.cscript.refresh = function(doc) {
if(cint(doc.is_local) && doc.has_serial_no) set_field_permlevel('has_serial_no', 1);
if(cint(doc.is_local) && doc.is_stock_item) set_field_permlevel('is_stock_item', 1);
}
cur_frm.fields_dict['default_bom'].get_query = function(doc) {
//var d = locals[this.doctype][this.docname];
return 'SELECT DISTINCT `tabBill Of Materials`.`name` FROM `tabBill Of Materials` WHERE `tabBill Of Materials`.`item` = "' + doc.item_code + '" AND `tabBill Of Materials`.`is_active` = "No" and `tabBill Of Materials`.docstatus != 2 AND `tabBill Of Materials`.%(key)s LIKE "%s" ORDER BY `tabBill Of Materials`.`name` LIMIT 50'
}
// Expense Account
// ---------------------------------
cur_frm.fields_dict['purchase_account'].get_query = function(doc){
return 'SELECT DISTINCT `tabAccount`.`name` FROM `tabAccount` WHERE `tabAccount`.`debit_or_credit`="Debit" AND `tabAccount`.`group_or_ledger`="Ledger" AND `tabAccount`.`docstatus`!=2 AND `tabAccount`.`is_pl_account` = "Yes" AND `tabAccount`.%(key)s LIKE "%s" ORDER BY `tabAccount`.`name` LIMIT 50'
}
// Income Account
// --------------------------------
cur_frm.fields_dict['default_income_account'].get_query = function(doc) {
return 'SELECT DISTINCT `tabAccount`.`name` FROM `tabAccount` WHERE `tabAccount`.`debit_or_credit`="Credit" AND `tabAccount`.`group_or_ledger`="Ledger" AND `tabAccount`.`is_pl_account` = "Yes" AND `tabAccount`.`docstatus`!=2 AND `tabAccount`.`account_type` ="Income Account" AND `tabAccount`.%(key)s LIKE "%s" ORDER BY `tabAccount`.`name` LIMIT 50'
}
// Purchase Cost Center
// -----------------------------
cur_frm.fields_dict['cost_center'].get_query = function(doc) {
return 'SELECT `tabCost Center`.`name` FROM `tabCost Center` WHERE `tabCost Center`.%(key)s LIKE "%s" AND `tabCost Center`.`group_or_ledger` = "Ledger" AND `tabCost Center`.`docstatus`!= 2 ORDER BY `tabCost Center`.`name` ASC LIMIT 50'
}
// Sales Cost Center
// -----------------------------
cur_frm.fields_dict['default_sales_cost_center'].get_query = function(doc) {
return 'SELECT `tabCost Center`.`name` FROM `tabCost Center` WHERE `tabCost Center`.%(key)s LIKE "%s" AND `tabCost Center`.`group_or_ledger` = "Ledger" AND `tabCost Center`.`docstatus`!= 2 ORDER BY `tabCost Center`.`name` ASC LIMIT 50'
}
cur_frm.fields_dict['item_tax'].grid.get_field("tax_type").get_query = function(doc, cdt, cdn) {
return 'SELECT `tabAccount`.`name` FROM `tabAccount` WHERE `tabAccount`.`account_type` in ("Tax", "Chargeable") and `tabAccount`.`docstatus` != 2 and `tabAccount`.%(key)s LIKE "%s" ORDER BY `tabAccount`.`name` DESC LIMIT 50'
}
cur_frm.cscript.tax_type = function(doc, cdt, cdn){
var d = locals[cdt][cdn];
get_server_fields('get_tax_rate',d.tax_type,'item_tax',doc, cdt, cdn, 1);
}
//get query select item group
cur_frm.fields_dict['item_group'].get_query = function(doc,cdt,cdn) {
return 'SELECT `tabItem Group`.`name`,`tabItem Group`.`parent_item_group` FROM `tabItem Group` WHERE `tabItem Group`.`is_group` = "No" AND `tabItem Group`.`docstatus`!= 2 AND `tabItem Group`.%(key)s LIKE "%s" ORDER BY `tabItem Group`.`name` ASC LIMIT 50'
}
cur_frm.cscript.IGHelp = function(doc,dt,dn){
var call_back = function(){
var sb_obj = new SalesBrowser();
sb_obj.set_val('Item Group');
}
loadpage('Sales Browser',call_back);
}
// for description from attachment
// takes the first attachment and creates
// a table with both image and attachment in HTML
// in the "alternate_description" field
cur_frm.cscript['Add Image'] = function(doc, dt, dn) {
if(!doc.file_list) {
msgprint('Please attach a file first!');
}
var f = doc.file_list.split('\n')[0];
var fname = f.split(',')[0];
var fid = f.split(',')[1];
if(!in_list(['jpg','jpeg','gif','png'], fname.split('.')[1].toLowerCase())) {
msgprint('File must be of extension jpg, jpeg, gif or png'); return;
}
doc.description_html = repl('<table style="width: 100%; table-layout: fixed;">'+
'<tr><td style="width:110px"><img src="%(imgurl)s" width="100px"></td>'+
'<td>%(desc)s</td></tr>'+
'</table>', {imgurl: wn.urllib.get_file_url(fid), desc:doc.description});
refresh_field('description_html');
}

View File

@@ -0,0 +1,177 @@
# Please edit this list and import only required elements
import webnotes
from webnotes.utils import add_days, add_months, add_years, cint, cstr, date_diff, default_fields, flt, fmt_money, formatdate, generate_hash, getTraceback, get_defaults, get_first_day, get_last_day, getdate, has_common, month_name, now, nowdate, replace_newlines, sendmail, set_default, str_esc_quote, user_format, validate_email_add
from webnotes.model import db_exists
from webnotes.model.doc import Document, addchild, removechild, getchildren, make_autoname, SuperDocType
from webnotes.model.doclist import getlist, copy_doclist
from webnotes.model.code import get_obj, get_server_obj, run_server_obj, updatedb, check_syntax
from webnotes import session, form, is_testing, msgprint, errprint
set = webnotes.conn.set
sql = webnotes.conn.sql
get_value = webnotes.conn.get_value
in_transaction = webnotes.conn.in_transaction
convert_to_lists = webnotes.conn.convert_to_lists
# -----------------------------------------------------------------------------------------
class DocType:
def __init__(self, doc, doclist=[]):
self.doc = doc
self.doclist = doclist
def get_tax_rate(self, tax_type):
rate = sql("select tax_rate from tabAccount where name = %s", tax_type)
ret = {
'tax_rate' : rate and flt(rate[0][0]) or 0
}
return str(ret)
def on_update(self):
bin = sql("select stock_uom from `tabBin` where item_code = '%s' " % self.doc.item_code)
if bin and cstr(bin[0][0]) != cstr(self.doc.stock_uom):
msgprint("Please Update Stock UOM with the help of Stock UOM Replace Utility.")
raise Exception
check_list = []
for d in getlist(self.doclist,'uom_conversion_details'):
if not self.doc.stock_uom:
msgprint("Please enter Stock UOM first.")
raise Exception
if cstr(d.uom) in check_list:
msgprint("UOM %s has been entered more than once in Conversion Factor Details." % cstr(d.uom))
raise Exception
if not cstr(d.uom) in check_list:
check_list.append(cstr(d.uom))
if cstr(d.uom) == cstr(self.doc.stock_uom):
if flt(d.conversion_factor) != 1:
msgprint("Conversion Fator of UOM : %s should be equal to 1. As UOM : %s is Stock UOM of Item: %s." % ( cstr(d.uom), cstr(d.uom), cstr(self.doc.name)))
raise Exception
# else set uom_exist as true
uom_exist='true'
elif cstr(d.uom) != cstr(self.doc.stock_uom) and flt(d.conversion_factor) == 1:
msgprint("Conversion Factor of UOM : %s should not be equal to 1. As UOM : %s is not Stock UOM of Item: %s." % ( cstr(d.uom), cstr(d.uom), cstr(self.doc.name)))
raise Exception
if not cstr(self.doc.stock_uom) in check_list :
child = addchild( self.doc, 'uom_conversion_details', 'UOM Conversion Detail', 1, self.doclist)
child.uom = self.doc.stock_uom
child.conversion_factor = 1
child.save()
# Check whether Ref Rate is not entered twice for same Price List and Currency
def check_ref_rate_detail(self):
check_list=[]
for d in getlist(self.doclist,'ref_rate_details'):
if [cstr(d.price_list_name),cstr(d.ref_currency)] in check_list:
msgprint("Ref Rate is entered twice for Price List : '%s' and Currency : '%s'." % (d.price_list_name,d.ref_currency))
raise Exception
else:
check_list.append([cstr(d.price_list_name),cstr(d.ref_currency)])
# Check whether Tax Rate is not entered twice for same Tax Type
def check_item_tax(self):
check_list=[]
for d in getlist(self.doclist,'item_tax'):
account_type = sql("select account_type from tabAccount where name = %s",d.tax_type)
account_type = account_type and account_type[0][0] or ''
if account_type not in ['Tax', 'Chargeable']:
msgprint("'%s' is not Tax / Chargeable Account"%(d.tax_type))
raise Exception, "Tax Account validation"
else:
if d.tax_type in check_list:
msgprint("Rate is entered twice for Tax : '%s'." % (d.tax_type))
raise Exception
else:
check_list.append(d.tax_type)
def check_for_active_boms(self, check):
if check in ['Is Active', 'Is Purchase Item']:
bom_mat = sql("select distinct t1.parent from `tabBOM Material` t1, `tabBill Of Materials` t2 where t1.item_code ='%s' and (t1.bom_no = '' or t1.bom_no is NULL) and t2.name = t1.parent and t2.is_active = 'Yes' and t2.docstatus = 1 and t1.docstatus =1 " % self.doc.name )
if bom_mat and bom_mat[0][0]:
msgprint("%s should be 'Yes'. As Item %s is present in one or many Active BOMs." % (cstr(check), cstr(self.doc.name)))
raise Exception
if check == 'Is Active' or ( check == 'Is Manufactured Item' and self.doc.is_sub_contracted_item != 'Yes') or (check == 'Is Sub Contracted Item' and self.doc.is_manufactured_item != 'Yes') :
bom = sql("select name from `tabBill Of Materials` where item = '%s' and is_active ='Yes'" % cstr(self.doc.name))
if bom and bom[0][0]:
msgprint("%s should be 'Yes'. As Item %s is present in one or many Active BOMs." % (cstr(check), cstr(self.doc.name)))
raise Exception
if check in ['Is Active', 'Is Pro Applicable']:
flat_bom = sql("select distinct t1.parent from `tabFlat BOM Detail` t1, `tabBill Of Materials` t2 where t1.item_code ='%s' and t2.name = t1.parent and t2.is_active = 'Yes' and t2.docstatus = 1 and t1.docstatus =1 and t1.is_pro_applicable = 'Yes'" % self.doc.name )
if flat_bom and flat_bom[0][0]:
msgprint(" %s should be 'Yes'. As Item %s is present in one or many Active BOMs." % (cstr(check), cstr(self.doc.name)))
raise Exception
def validate(self):
fl = {'is_manufactured_item' :'Is Manufactured Item',
'is_sub_contracted_item':'Is Sub Contracted Item',
'is_purchase_item' :'Is Purchase Item',
'is_pro_applicable' :'Is Pro Applicable'}
for d in fl:
if cstr(self.doc.fields[d]) != 'Yes':
self.check_for_active_boms(check = fl[d])
self.check_ref_rate_detail()
self.check_item_tax()
if not self.doc.min_order_qty:
self.doc.min_order_qty = 0
self.check_non_asset_warehouse()
if self.doc.is_pro_applicable == 'Yes' and self.doc.is_manufactured_item != 'Yes':
msgprint("If making Production Order is allowed then, it should also allow to make Bill of Materials. Refer Manufacturing section.")
raise Exception
if self.doc.is_pro_applicable == 'Yes' and self.doc.is_stock_item == 'No':
msgprint("As Production Order can be made for this Item, then Is Stock Item Should be 'Yes' as we maintain it's stock. Refer Manufacturing and Inventory section.", raise_exception=1)
if self.doc.is_stock_item == "Yes" and not self.doc.default_warehouse:
msgprint("As we maintain stock of this item, its better to maintain default warehouse. To add default warehouse please go to 'Inventory' section. It will be fetched automatically while making Sales Order, Delivery Note, etc.. ", 1)
if self.doc.has_serial_no == 'Yes' and self.doc.is_stock_item == 'No':
msgprint("'Has Serial No' can not be 'Yes' for non-stock item", raise_exception=1)
def check_non_asset_warehouse(self):
if self.doc.is_asset_item == "Yes":
existing_qty = sql("select t1.warehouse, t1.actual_qty from tabBin t1, tabWarehouse t2 where t1.item_code=%s and (t2.warehouse_type!='Fixed Asset' or t2.warehouse_type is null) and t1.warehouse=t2.name and t1.actual_qty > 0", self.doc.name)
for e in existing_qty:
msgprint("%s Units exist in Warehouse %s, which is not an Asset Warehouse." % (e[1],e[0]))
if existing_qty:
msgprint("Please transfer the above quantities to an asset warehouse before changing this item to an asset item.")
self.doc.is_asset_item = 'No'
raise Exception
def check_min_inventory_level(self):
if self.doc.minimum_inventory_level:
total_qty = sql("select sum(projected_qty) from tabBin where item_code = %s",self.doc.name)
if flt(total_qty) < flt(self.doc.minimum_inventory_level):
msgprint("Your minimum inventory level is reached")
send_to = []
send = sql("select t1.email from `tabProfile` t1,`tabUserRole` t2 where t2.role IN ('Material Master Manager','Purchase Manager') and t2.parent = t1.name")
for d in send:
send_to.append(d[0])
msg = '''
Minimum Inventory Level Reached
Item Code: %s
Item Name: %s
Minimum Inventory Level: %s
Total Available Qty: %s
''' % (self.doc.item_code, self.doc.item_name, self.doc.minimum_inventory_level, total_qty)
sendmail(send_to, sender='automail@webnotestech.com', subject='Minimum Inventory Level Reached', parts=[['text/plain', msg]])
def get_file_details(self, arg = ''):
file = sql("select file_group, description from tabFile where name = %s", eval(arg)['file_name'], as_dict = 1)
ret = {
'file_group' : file and file[0]['file_group'] or '',
'description' : file and file[0]['description'] or ''
}
return str(ret)

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1 @@
[{'section_style': 'Simple', 'is_transaction_doc': None, 'creation': '2009-08-10 15:46:04', 'search_fields': None, 'module': 'Material Management', 'doctype': 'DocType', 'change_log': None, 'print_outline': '', 'owner': 'Administrator', 'in_dialog': None, 'in_create': None, 'read_only': None, 'allow_email': None, 'dt_template': None, 'hide_heading': None, 'issingle': None, 'allow_rename': None, 'smallicon': None, 'allow_attach': None, 'show_in_menu': 0, 'max_attachments': None, 'version': 6, 'menu_index': None, 'docstatus': 0, 'allow_copy': None, 'istable': 1, 'description': None, 'parent': None, 'server_code': None, 'allow_trash': None, 'allow_print': None, 'autoname': None, 'client_script_core': None, 'client_string': None, 'use_template': None, 'modified_by': 'Administrator', 'document_type': None, 'name': 'Item Attachments Detail', 'idx': None, 'hide_toolbar': None, 'colour': 'White:FFF', 'client_script': None, 'modified': '2010-09-20 14:06:57', 'server_code_error': ' ', 'name_case': '', 'parenttype': None, 'read_only_onload': None, 'server_code_core': None, 'server_code_compiled': None, 'parent_node': None, 'parentfield': None}, {'no_copy': None, 'oldfieldtype': 'Link', 'creation': '2009-08-10 15:46:04', 'doctype': 'DocField', 'oldfieldname': 'file_name', 'owner': 'Administrator', 'reqd': None, 'in_filter': None, 'print_hide': None, 'modified_by': 'Administrator', 'label': 'File Name', 'width': '220px', 'trigger': 'Client', 'depends_on': None, 'docstatus': 0, 'hidden': None, 'permlevel': 0, 'description': None, 'parent': 'Item Attachments Detail', 'search_index': None, 'allow_on_submit': None, 'icon': None, 'name': 'FL02701', 'idx': 1, 'default': None, 'colour': None, 'modified': '2009-08-10 17:07:02', 'parenttype': 'DocType', 'fieldname': 'file_name', 'fieldtype': 'Link', 'options': 'File', 'report_hide': None, 'parentfield': 'fields'}, {'no_copy': None, 'oldfieldtype': 'Data', 'creation': '2009-08-10 15:46:04', 'doctype': 'DocField', 'oldfieldname': 'file_group', 'owner': 'Administrator', 'reqd': None, 'in_filter': None, 'print_hide': None, 'modified_by': 'Administrator', 'label': 'File Group', 'width': '160px', 'trigger': None, 'depends_on': None, 'docstatus': 0, 'hidden': None, 'permlevel': 1, 'description': None, 'parent': 'Item Attachments Detail', 'search_index': None, 'allow_on_submit': None, 'icon': None, 'name': 'FL02702', 'idx': 2, 'default': None, 'colour': None, 'modified': '2009-08-10 17:07:02', 'parenttype': 'DocType', 'fieldname': 'file_group', 'fieldtype': 'Data', 'options': None, 'report_hide': None, 'parentfield': 'fields'}, {'no_copy': None, 'oldfieldtype': 'Text', 'creation': '2009-08-10 15:46:04', 'doctype': 'DocField', 'oldfieldname': 'description', 'owner': 'Administrator', 'reqd': None, 'in_filter': None, 'print_hide': None, 'modified_by': 'Administrator', 'label': 'Description', 'width': '300px', 'trigger': None, 'depends_on': None, 'docstatus': 0, 'hidden': None, 'permlevel': 1, 'description': None, 'parent': 'Item Attachments Detail', 'search_index': None, 'allow_on_submit': None, 'icon': None, 'name': 'FL02703', 'idx': 3, 'default': None, 'colour': None, 'modified': '2009-08-10 17:07:02', 'parenttype': 'DocType', 'fieldname': 'description', 'fieldtype': 'Text', 'options': None, 'report_hide': None, 'parentfield': 'fields'}]

View File

@@ -0,0 +1 @@
[{'section_style': 'Simple', 'is_transaction_doc': None, 'creation': '2009-03-28 13:08:08', 'search_fields': None, 'module': 'Material Management', 'doctype': 'DocType', 'change_log': None, 'print_outline': '', 'owner': 'Administrator', 'in_dialog': None, 'in_create': None, 'read_only': None, 'allow_email': None, 'dt_template': None, 'hide_heading': None, 'issingle': None, 'allow_rename': None, 'smallicon': None, 'allow_attach': None, 'show_in_menu': 0, 'max_attachments': None, 'version': 1, 'menu_index': None, 'docstatus': 0, 'allow_copy': None, 'istable': 1, 'description': None, 'parent': None, 'server_code': None, 'allow_trash': None, 'allow_print': None, 'autoname': 'IISD/.#####', 'client_script_core': None, 'client_string': None, 'use_template': None, 'modified_by': 'nabin@webnotestech.com', 'document_type': None, 'name': 'Item Specification Detail', 'idx': None, 'hide_toolbar': None, 'colour': 'White:FFF', 'client_script': None, 'modified': '2010-09-20 14:06:57', 'server_code_error': ' ', 'name_case': '', 'parenttype': None, 'read_only_onload': None, 'server_code_core': None, 'server_code_compiled': None, 'parent_node': None, 'parentfield': None}, {'no_copy': None, 'oldfieldtype': 'Data', 'creation': '2009-03-28 13:08:09', 'doctype': 'DocField', 'oldfieldname': 'specification', 'owner': 'Administrator', 'reqd': 1, 'in_filter': 0, 'print_hide': None, 'modified_by': 'nabin@webnotestech.com', 'label': 'Parameter', 'width': '200px', 'trigger': None, 'depends_on': None, 'docstatus': 0, 'hidden': None, 'permlevel': 0, 'description': None, 'parent': 'Item Specification Detail', 'search_index': 0, 'allow_on_submit': None, 'icon': None, 'name': 'FL01536', 'idx': 1, 'default': None, 'colour': None, 'modified': '2010-05-07 10:17:01', 'parenttype': 'DocType', 'fieldname': 'specification', 'fieldtype': 'Data', 'options': None, 'report_hide': None, 'parentfield': 'fields'}, {'no_copy': None, 'oldfieldtype': 'Data', 'creation': '2009-03-28 13:08:09', 'doctype': 'DocField', 'oldfieldname': 'value', 'owner': 'Administrator', 'reqd': None, 'in_filter': None, 'print_hide': None, 'modified_by': 'nabin@webnotestech.com', 'label': 'Acceptance Criteria', 'width': None, 'trigger': None, 'depends_on': None, 'docstatus': 0, 'hidden': None, 'permlevel': 0, 'description': None, 'parent': 'Item Specification Detail', 'search_index': None, 'allow_on_submit': None, 'icon': None, 'name': 'FL01537', 'idx': 2, 'default': None, 'colour': None, 'modified': '2010-05-07 10:17:01', 'parenttype': 'DocType', 'fieldname': 'value', 'fieldtype': 'Data', 'options': None, 'report_hide': None, 'parentfield': 'fields'}]

View File

@@ -0,0 +1 @@
[{'section_style': 'Tray', 'is_transaction_doc': None, 'creation': '2009-04-07 12:11:58', 'search_fields': None, 'module': 'Material Management', 'doctype': 'DocType', 'change_log': None, 'print_outline': '', 'owner': 'Administrator', 'in_dialog': None, 'in_create': None, 'read_only': None, 'allow_email': None, 'dt_template': None, 'hide_heading': None, 'issingle': None, 'allow_rename': None, 'smallicon': None, 'allow_attach': None, 'show_in_menu': 0, 'max_attachments': None, 'version': None, 'menu_index': None, 'docstatus': 0, 'allow_copy': None, 'istable': 1, 'description': None, 'parent': None, 'server_code': None, 'allow_trash': None, 'allow_print': None, 'autoname': None, 'client_script_core': None, 'client_string': None, 'use_template': None, 'modified_by': 'Administrator', 'document_type': None, 'name': 'Item Tax', 'idx': None, 'hide_toolbar': None, 'colour': 'White:FFF', 'client_script': None, 'modified': '2010-09-20 14:06:57', 'server_code_error': ' ', 'name_case': '', 'parenttype': None, 'read_only_onload': None, 'server_code_core': None, 'server_code_compiled': None, 'parent_node': None, 'parentfield': None}, {'no_copy': None, 'oldfieldtype': 'Link', 'creation': '2009-04-07 12:11:58', 'doctype': 'DocField', 'oldfieldname': 'tax_type', 'owner': 'Administrator', 'reqd': 1, 'in_filter': None, 'print_hide': None, 'modified_by': 'Administrator', 'label': 'Tax', 'width': None, 'trigger': 'Client', 'depends_on': None, 'docstatus': 0, 'hidden': None, 'permlevel': 0, 'description': None, 'parent': 'Item Tax', 'search_index': None, 'allow_on_submit': None, 'icon': None, 'name': 'FL01724', 'idx': 1, 'default': None, 'colour': None, 'modified': '2009-04-07 12:25:25', 'parenttype': 'DocType', 'fieldname': 'tax_type', 'fieldtype': 'Link', 'options': 'Account', 'report_hide': None, 'parentfield': 'fields'}, {'no_copy': None, 'oldfieldtype': 'Currency', 'creation': '2009-04-07 12:11:58', 'doctype': 'DocField', 'oldfieldname': 'tax_rate', 'owner': 'Administrator', 'reqd': 0, 'in_filter': None, 'print_hide': None, 'modified_by': 'Administrator', 'label': 'Tax Rate', 'width': None, 'trigger': None, 'depends_on': None, 'docstatus': 0, 'hidden': None, 'permlevel': 0, 'description': None, 'parent': 'Item Tax', 'search_index': None, 'allow_on_submit': None, 'icon': None, 'name': 'FL01725', 'idx': 2, 'default': None, 'colour': None, 'modified': '2009-04-07 12:25:25', 'parenttype': 'DocType', 'fieldname': 'tax_rate', 'fieldtype': 'Currency', 'options': None, 'report_hide': None, 'parentfield': 'fields'}]

View File

@@ -0,0 +1,10 @@
$import(Tips Common)
//--------- ONLOAD -------------
cur_frm.cscript.onload = function(doc, cdt, cdn) {
cur_frm.cscript.get_tips(doc, cdt, cdn);
}
cur_frm.cscript.refresh = function(doc, cdt, cdn) {
cur_frm.cscript.get_tips(doc, cdt, cdn);
}

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1 @@
[{'section_style': 'Simple', 'is_transaction_doc': None, 'creation': '2010-07-27 15:30:16', 'search_fields': None, 'module': 'Material Management', 'doctype': 'DocType', 'change_log': None, 'print_outline': '', 'owner': 'Administrator', 'in_dialog': None, 'in_create': None, 'read_only': None, 'allow_email': None, 'dt_template': None, 'hide_heading': None, 'issingle': None, 'allow_rename': None, 'smallicon': '', 'allow_attach': None, 'show_in_menu': None, 'max_attachments': None, 'version': 2, 'menu_index': None, 'docstatus': 0, 'allow_copy': None, 'istable': 1, 'description': None, 'parent': None, 'server_code': None, 'allow_trash': None, 'allow_print': None, 'autoname': None, 'client_script_core': None, 'client_string': None, 'use_template': None, 'modified_by': 'saumil@webnotestech.com', 'document_type': None, 'name': 'Landed Cost Master Detail', 'idx': None, 'hide_toolbar': None, 'colour': 'White:FFF', 'client_script': None, 'modified': '2010-09-20 14:06:57', 'server_code_error': ' ', 'name_case': '', 'parenttype': None, 'read_only_onload': None, 'server_code_core': None, 'server_code_compiled': None, 'parent_node': None, 'parentfield': None}, {'no_copy': None, 'oldfieldtype': 'Data', 'creation': '2010-07-27 15:30:17', 'doctype': 'DocField', 'oldfieldname': 'account_head', 'owner': 'Administrator', 'reqd': None, 'in_filter': None, 'print_hide': None, 'modified_by': 'saumil@webnotestech.com', 'label': 'Account Head', 'width': None, 'trigger': None, 'depends_on': None, 'docstatus': 0, 'hidden': None, 'permlevel': 0, 'description': None, 'parent': 'Landed Cost Master Detail', 'search_index': None, 'allow_on_submit': None, 'icon': None, 'name': 'FL05709', 'idx': 1, 'default': None, 'colour': None, 'modified': '2010-08-08 14:52:23', 'parenttype': 'DocType', 'fieldname': 'account_head', 'fieldtype': 'Data', 'options': None, 'report_hide': None, 'parentfield': 'fields'}, {'no_copy': None, 'oldfieldtype': 'Data', 'creation': '2010-07-27 15:30:17', 'doctype': 'DocField', 'oldfieldname': 'description', 'owner': 'Administrator', 'reqd': None, 'in_filter': None, 'print_hide': None, 'modified_by': 'saumil@webnotestech.com', 'label': 'Description', 'width': None, 'trigger': None, 'depends_on': None, 'docstatus': 0, 'hidden': None, 'permlevel': 0, 'description': None, 'parent': 'Landed Cost Master Detail', 'search_index': None, 'allow_on_submit': None, 'icon': None, 'name': 'FL05710', 'idx': 2, 'default': None, 'colour': None, 'modified': '2010-08-08 14:52:23', 'parenttype': 'DocType', 'fieldname': 'description', 'fieldtype': 'Data', 'options': None, 'report_hide': None, 'parentfield': 'fields'}]

View File

@@ -0,0 +1,11 @@
cur_frm.cscript.onload = function(doc, cdt, cdn) {
if(!doc.currency){doc.currency = sys_defaults.currency;}
}
cur_frm.fields_dict['landed_cost_details'].grid.get_field("account_head").get_query = function(doc,cdt,cdn) {
return 'SELECT tabAccount.name FROM tabAccount WHERE tabAccount.group_or_ledger="Ledger" AND tabAccount.docstatus != 2 AND tabAccount.account_type = "Chargeable" AND tabAccount.name LIKE "%s"'
}
cur_frm.fields_dict['landed_cost_details'].grid.get_field("account_head").get_query = function(doc,cdt,cdn) {
return 'SELECT tabAccount.name FROM tabAccount WHERE tabAccount.group_or_ledger="Ledger" AND tabAccount.docstatus != 2 AND (tabAccount.account_type = "Tax" OR tabAccount.account_type = "Chargeable") AND tabAccount.name LIKE "%s"'
}

View File

@@ -0,0 +1,241 @@
# Please edit this list and import only required elements
import webnotes
from webnotes.utils import add_days, add_months, add_years, cint, cstr, date_diff, default_fields, flt, fmt_money, formatdate, generate_hash, getTraceback, get_defaults, get_first_day, get_last_day, getdate, has_common, month_name, now, nowdate, replace_newlines, sendmail, set_default, str_esc_quote, user_format, validate_email_add
from webnotes.model import db_exists
from webnotes.model.doc import Document, addchild, removechild, getchildren, make_autoname, SuperDocType
from webnotes.model.doclist import getlist, copy_doclist
from webnotes.model.code import get_obj, get_server_obj, run_server_obj, updatedb, check_syntax
from webnotes import session, form, is_testing, msgprint, errprint
set = webnotes.conn.set
sql = webnotes.conn.sql
get_value = webnotes.conn.get_value
in_transaction = webnotes.conn.in_transaction
convert_to_lists = webnotes.conn.convert_to_lists
# -----------------------------------------------------------------------------------------
class DocType:
def __init__(self, doc, doclist=[]):
self.doc = doc
self.doclist = doclist
def get_purchase_receipts(self):
self.doc.clear_table(self.doclist,'lc_pr_details',1)
if not self.doc.from_pr_date or not self.doc.to_pr_date:
msgprint("Please enter From and To PR Date")
raise Exception
if not self.doc.currency:
msgprint("Please enter Currency.")
raise Exception
pr = sql("select name from `tabPurchase Receipt` where docstatus = 1 and posting_date >= '%s' and posting_date <= '%s' and currency = '%s' order by name "%(self.doc.from_pr_date,self.doc.to_pr_date,self.doc.currency), as_dict = 1)
if len(pr)>200:
msgprint("Please enter date of shorter duration as there are too many purchase receipt, hence it cannot be loaded.")
raise Exception
for i in pr:
if i and i['name']:
pr_no = addchild(self.doc, 'lc_pr_details', 'LC PR Detail', 1, self.doclist)
pr_no.purchase_receipt_no = i and i['name'] or ''
pr_no.save()
def update_pr_lc_se(self):
lst = []
condition = ' name in('
amt = 0
for d in getlist(self.doclist, 'lc_pr_details'):
if cint(d.include_in_landed_cost) == 1:
condition += '"'+d.purchase_receipt_no+'",'
lst.append(d.purchase_receipt_no)
condition += '"")'
amount = sql("SELECT SUM(net_total) FROM `tabPurchase Receipt` WHERE docstatus = 1 AND %s"%condition)
amt = amount and flt(amount[0][0]) or 0
for lc in getlist(self.doclist, 'landed_cost_details'):
for name in lst:
pr_oc_det = sql("select name from `tabPurchase Tax Detail` where parent = %s and category = 'For Valuation' and add_deduct_tax = 'Add' and charge_type = 'Actual' and account_head = %s ",(name, lc.account_head))
#obj = get_obj('Purchase Receipt', name, with_children = 1)
if not pr_oc_det:
obj = get_obj('Purchase Receipt', name, with_children = 1)
lgth = cint(sql("select count(name) from `tabPurchase Tax Detail` where parent = '%s' "%(name))[0][0])
pr_oc = addchild(obj.doc, 'purchase_tax_details', 'Purchase Tax Detail', 1)
pr_oc.category = 'For Valuation'
pr_oc.add_deduct_tax = 'Add'
pr_oc.charge_type = 'Actual'
pr_oc.description = lc.description
pr_oc.account_head = lc.account_head
pr_oc.rate = flt(flt(lc.amount) * flt(obj.doc.net_total/ amt))
pr_oc.tax_amount = flt(flt(lc.amount) * flt(obj.doc.net_total/ amt))
pr_oc.total = obj.doc.grand_total
pr_oc.docstatus = 1
pr_oc.idx = cint(lgth)
pr_oc.save()
else:
obj = get_obj('Purchase Receipt', name)
sql("update `tabPurchase Tax Detail` set rate = %s, tax_amount = %s where name = %s and parent = %s",(flt(flt(lc.amount) * flt(obj.doc.net_total/ amt)),flt(flt(lc.amount) * flt(obj.doc.net_total/ amt)),pr_oc_det[0][0],name))
self.calc_pr_other_charges(name)
obj = get_obj('Purchase Receipt', name, with_children = 1)
for d in getlist(obj.doclist, 'purchase_receipt_details'):
if flt(d.qty):
d.valuation_rate = (flt(d.purchase_rate) + (flt(d.rm_supp_cost) / flt(d.qty)) + (flt(d.item_tax_amount)/flt(d.qty))) / flt(d.conversion_factor)
d.save()
sql("update `tabStock Ledger Entry` set incoming_rate = '%s' where voucher_detail_no = '%s'"%(flt(d.valuation_rate), d.name))
bin_name = sql("select t1.name, t2.name, t2.posting_date, t2.posting_time from `tabBin` t1, `tabStock Ledger Entry` t2 where t2.voucher_detail_no = '%s' and t2.item_code = t1.item_code and t2.warehouse = t1.warehouse LIMIT 1"%(d.name))
if bin_name and bin_name[0][0]:
obj = get_obj('Bin', bin_name[0][0]).update_item_valuation(bin_name[0][1], bin_name[0][2], bin_name[0][3])
# now distribute the taxes among the PRs
for lc in getlist(self.doclist, 'landed_cost_details'):
for d in lst:
pr_id = d.purchase_receipt_no
# load the purchase receipt object
pr = get_obj('Purchase Receipt', pr_id, with_children = 1)
# get the tax detail (for valuation) in the PR if it exists
pr_oc_det = sql("select name from `tabPurchase Tax Detail` where parent = %s and category = 'For Valuation' and add_deduct_tax = 'Add' and charge_type = 'Actual' and account_head = %s ",(pr_id, lc.account_head))
# update tax rate and tax amount
tax_amount = flt(flt(lc.amount) * flt(pr.doc.net_total/ amt))
# for display
d.net_total = pr.doc.net_total
d.added_cost = tax_amount
d.save()
# if not exist, create the tax detail for valuation
if not pr_oc_det:
lgth = cint(sql("select count(name) from `tabPurchase Tax Detail` where parent = '%s' "%(pr_id))[0][0])
pr_oc = addchild(pr.doc, 'purchase_tax_details', 'Purchase Tax Detail', 1)
pr_oc.category = 'For Valuation'
pr_oc.add_deduct_tax = 'Add'
pr_oc.charge_type = 'Actual'
pr_oc.description = lc.description
pr_oc.account_head = lc.account_head
pr_oc.rate = tax_amount
pr_oc.tax_amount = tax_amount
pr_oc.total = obj.doc.grand_total
pr_oc.docstatus = 1
pr_oc.idx = cint(lgth)
pr_oc.save()
else:
obj = get_obj('Purchase Receipt', name)
sql("update `tabPurchase Tax Detail` set rate = %s, tax_amount = %s where name = %s and parent = %s", \
(tax_amount, tax_amount, pr_oc_det[0][0], pr_id))
self.calc_pr_other_charges(name)
# reload - and update the stock entries with the
# additional valuations
obj = get_obj('Purchase Receipt', name, with_children = 1)
for d in getlist(obj.doclist, 'purchase_receipt_details'):
if flt(d.qty):
d.valuation_rate = (flt(d.purchase_rate) + (flt(d.rm_supp_cost) / flt(d.qty)) + (flt(d.item_tax_amount)/flt(d.qty))) / flt(d.conversion_factor)
d.save()
sql("update `tabStock Ledger Entry` set incoming_rate = '%s' where voucher_detail_no = '%s'"%(flt(d.valuation_rate), d.name))
bin_name = sql("select t1.name, t2.name, t2.posting_date, t2.posting_time from `tabBin` t1, `tabStock Ledger Entry` t2 where t2.voucher_detail_no = '%s' and t2.item_code = t1.item_code and t2.warehouse = t1.warehouse LIMIT 1"%(d.name))
# update valuation of the item
if bin_name and bin_name[0][0]:
obj = get_obj('Bin', bin_name[0][0]).update_item_valuation(bin_name[0][1], bin_name[0][2], bin_name[0][3])
def add_deduct_taxes(self, ocd, oc, tax_amount, total_amount, total, prev_total, f=1):
ocd[oc].total_amount = flt(tax_amount.toFixed(2))
ocd[oc].total_tax_amount = flt(prev_total.toFixed(2))
ocd[oc].tax_amount += flt(tax_amount.toFixed(2))
total_amount = flt(ocd[oc].tax_amount)
total_tax_amount = flt(ocd[oc].total_tax_amount) + (f * flt(total_amount))
if ocd[oc].category != "For Valuation":
prev_total += f * flt(ocd[oc].total_amount)
total += f * flt(ocd[oc].tax_amount)
ocd[oc].total = flt(total) + (f * flt(tax[t].tax_amount))
else:
prev_total = prev_total
ocd[oc].total = flt(total)
if ocd[oc].category != "For Total":
item_tax += f * ocd[oc].total_amount
ocd[oc].save()
return total, prev_total
# calculate the taxes for these PRs
def calc_pr_other_charges(self, name):
# re-calculate other charges
obj = get_obj('Purchase Receipt', name, with_children = 1)
total = 0
net_total = obj.doc.net_total
for prd in getlist(obj.doclist, 'purchase_receipt_details'):
prev_total, item_tax = flt(prd.amount), 0
total += flt(flt(prd.qty) * flt(prd.purchase_rate))
check_tax = prd.item_tax_rate and eval(prd.item_tax_rate) or {}
ocd = getlist(obj.doclist, 'purchase_tax_details')
# calculate tax for other charges
for oc in range(len(ocd)):
if check_tax.get(ocd[oc].account_head) and ocd[oc].charge_type != 'Actual':
rate = check_tax[ocd[oc].account_head]
else:
rate = flt(ocd[oc].rate)
tax_amount = self.cal_tax(ocd, prd, rate, net_total, oc)
if ocd[oc].add_deduct_tax == 'Add':
add_deduct_taxes(self, ocd, oc, tax_amount, total_amount, total, prev_total, f=1)
elif ocd[oc].add_deduct_tax == 'Deduct':
add_deduct_taxes(self, ocd, oc, tax_amount, total_amount, total, prev_total, f=-1)
prd.item_tax_amount = flt(item_tax)
prd.save()
obj.doc.save()
def cal_tax(self, ocd, prd, rate, net_total, oc):
tax_amount = 0
if ocd[oc].charge_type == 'Actual':
value = flt(flt(rate) / flt(net_total))
return flt(flt(value) * flt(prd.amount))
elif ocd[oc].charge_type == 'On Net Total':
return flt(flt(rate) * flt(prd.amount) / 100)
elif ocd[oc].charge_type == 'On Previous Row Amount':
row_no = cstr(ocd[oc].row_id)
row = (row_no).split("+")
for r in range(0, len(row.length)):
id = cint(row[r])
tax_amount += flt((flt(rate) * flt(ocd[id-1].total_amount) / 100))
row_id = row_no.find("/")
if row_id != -1:
rate = ''
row = (row_no).split("/")
id1 = cint(row[0])
id2 = cint(row[1])
tax_amount = flt(flt(ocd[id1-1].total_amount) / flt(ocd[id2-1].total_amount))
return tax_amount
# get details for landed cost table from master
# ---------------------------------------------
def get_landed_cost_master_details(self):
msgprint('fetching details.....' + self.doc.landed_cost)
self.doc.clear_table(self.doclist, 'landed_cost_details')
idx = 0
landed_cost = sql("select account_head, description from `tabLanded Cost Master Detail` where parent=%s", (self.doc.landed_cost), as_dict = 1)
msgprint(landed_cost)
for cost in landed_cost:
lct = addchild(self.doc, 'landed_cost_details', 'Landed Cost Detail', 1, self.doclist)
lct.account_head = cost['account_head']
lct.description = cost['description']

View File

@@ -0,0 +1,660 @@
[
{
'_last_update': '1303877045',
'allow_attach': None,
'allow_copy': None,
'allow_email': None,
'allow_print': None,
'allow_rename': None,
'allow_trash': None,
'autoname': None,
'change_log': None,
'client_script': None,
'client_script_core': None,
'client_string': None,
'colour': 'White:FFF',
'creation': '2010-08-08 17:09:07',
'description': None,
'docstatus': 0,
'doctype': 'DocType',
'document_type': None,
'dt_template': None,
'hide_heading': None,
'hide_toolbar': None,
'idx': None,
'in_create': None,
'in_dialog': None,
'is_transaction_doc': None,
'issingle': 1,
'istable': None,
'max_attachments': None,
'menu_index': None,
'modified': '2011-04-27 09:36:36',
'modified_by': 'Administrator',
'module': 'Material Management',
'name': 'Landed Cost Wizard',
'name_case': None,
'owner': None,
'parent': None,
'parent_node': '',
'parentfield': None,
'parenttype': None,
'print_outline': None,
'read_only': None,
'read_only_onload': None,
'search_fields': None,
'section_style': 'Simple',
'server_code': None,
'server_code_compiled': None,
'server_code_core': None,
'server_code_error': ' ',
'show_in_menu': 1,
'smallicon': None,
'use_template': None,
'version': 33
},
{
'amend': None,
'cancel': None,
'create': None,
'creation': '2010-08-08 17:09:07',
'docstatus': 0,
'doctype': 'DocPerm',
'execute': None,
'idx': 1,
'match': None,
'modified': '2011-04-27 09:36:36',
'modified_by': 'Administrator',
'name': 'PERM00306',
'owner': 'wasim@webnotestech.com',
'parent': 'Landed Cost Wizard',
'parentfield': 'permissions',
'parenttype': 'DocType',
'permlevel': 0,
'read': 1,
'role': 'All',
'submit': None,
'write': 0
},
{
'amend': 0,
'cancel': 0,
'create': 1,
'creation': '2010-08-08 17:09:07',
'docstatus': 0,
'doctype': 'DocPerm',
'execute': None,
'idx': 2,
'match': None,
'modified': '2011-04-27 09:36:36',
'modified_by': 'Administrator',
'name': 'PERM00307',
'owner': 'wasim@webnotestech.com',
'parent': 'Landed Cost Wizard',
'parentfield': 'permissions',
'parenttype': 'DocType',
'permlevel': 0,
'read': 1,
'role': 'Purchase Manager',
'submit': 0,
'write': 1
},
{
'amend': None,
'cancel': None,
'create': 1,
'creation': '2010-08-08 17:09:07',
'docstatus': 0,
'doctype': 'DocPerm',
'execute': None,
'idx': 3,
'match': None,
'modified': '2011-04-27 09:36:36',
'modified_by': 'Administrator',
'name': 'PERM00308',
'owner': 'wasim@webnotestech.com',
'parent': 'Landed Cost Wizard',
'parentfield': 'permissions',
'parenttype': 'DocType',
'permlevel': 0,
'read': 1,
'role': 'Administrator',
'submit': None,
'write': 1
},
{
'amend': None,
'cancel': None,
'create': 1,
'creation': '2010-08-08 17:09:07',
'docstatus': 0,
'doctype': 'DocPerm',
'execute': None,
'idx': 4,
'match': None,
'modified': '2011-04-27 09:36:36',
'modified_by': 'Administrator',
'name': 'PERM00309',
'owner': 'wasim@webnotestech.com',
'parent': 'Landed Cost Wizard',
'parentfield': 'permissions',
'parenttype': 'DocType',
'permlevel': 0,
'read': 1,
'role': 'Purchase User',
'submit': None,
'write': 1
},
{
'amend': None,
'cancel': None,
'create': None,
'creation': '2010-08-08 17:09:07',
'docstatus': 0,
'doctype': 'DocPerm',
'execute': None,
'idx': 5,
'match': None,
'modified': '2011-04-27 09:36:36',
'modified_by': 'Administrator',
'name': 'PERM00310',
'owner': 'wasim@webnotestech.com',
'parent': 'Landed Cost Wizard',
'parentfield': 'permissions',
'parenttype': 'DocType',
'permlevel': 1,
'read': 1,
'role': 'All',
'submit': None,
'write': None
},
{
'amend': None,
'cancel': None,
'create': None,
'creation': '2010-08-08 17:09:07',
'docstatus': 0,
'doctype': 'DocPerm',
'execute': None,
'idx': 6,
'match': None,
'modified': '2011-04-27 09:36:36',
'modified_by': 'Administrator',
'name': 'PERM00311',
'owner': 'wasim@webnotestech.com',
'parent': 'Landed Cost Wizard',
'parentfield': 'permissions',
'parenttype': 'DocType',
'permlevel': 1,
'read': 1,
'role': 'Administrator',
'submit': None,
'write': None
},
{
'amend': None,
'cancel': None,
'create': None,
'creation': '2010-08-08 17:09:07',
'docstatus': 0,
'doctype': 'DocPerm',
'execute': None,
'idx': 7,
'match': None,
'modified': '2011-04-27 09:36:36',
'modified_by': 'Administrator',
'name': 'PERM00312',
'owner': 'wasim@webnotestech.com',
'parent': 'Landed Cost Wizard',
'parentfield': 'permissions',
'parenttype': 'DocType',
'permlevel': 1,
'read': 1,
'role': 'Purchase User',
'submit': None,
'write': None
},
{
'amend': None,
'cancel': None,
'create': None,
'creation': '2010-08-08 17:09:07',
'docstatus': 0,
'doctype': 'DocPerm',
'execute': None,
'idx': 8,
'match': None,
'modified': '2011-04-27 09:36:36',
'modified_by': 'Administrator',
'name': 'PERM00313',
'owner': 'wasim@webnotestech.com',
'parent': 'Landed Cost Wizard',
'parentfield': 'permissions',
'parenttype': 'DocType',
'permlevel': 1,
'read': 1,
'role': 'Purchase Manager',
'submit': None,
'write': None
},
{
'allow_on_submit': None,
'colour': None,
'creation': '2011-04-27 09:34:05',
'default': None,
'depends_on': None,
'description': None,
'docstatus': 0,
'doctype': 'DocField',
'fieldname': None,
'fieldtype': 'HTML',
'hidden': None,
'icon': None,
'idx': 1,
'in_filter': None,
'label': 'Landed Cost Help',
'modified': '2011-04-27 09:36:36',
'modified_by': 'Administrator',
'name': '000000649',
'no_copy': None,
'oldfieldname': None,
'oldfieldtype': None,
'options': '<div class=\'info-box\'>\nThis wizard helps you add costs to your item valuation. This is useful in cases where the true item cost is know after the items have been accepted in the warehouse. For example if your freight and clearing charges are known much later, hence the term "Landed Cost" <br><br>\n<b>How to use this wizard?</b>\n<ol>\n<li>Select the Purchase Receipts on whose items to want to add the costs</li>\n<li>Enter the costs in the second table</li>\n<li>Click on Update PR</li>\n</ol>\n</div>',
'owner': 'Administrator',
'parent': 'Landed Cost Wizard',
'parentfield': 'fields',
'parenttype': 'DocType',
'permlevel': 0,
'print_hide': None,
'report_hide': None,
'reqd': None,
'search_index': None,
'trigger': None,
'width': None
},
{
'allow_on_submit': None,
'colour': None,
'creation': '2010-08-08 17:09:07',
'default': None,
'depends_on': None,
'description': None,
'docstatus': 0,
'doctype': 'DocField',
'fieldname': 'from_pr_date',
'fieldtype': 'Date',
'hidden': None,
'icon': None,
'idx': 2,
'in_filter': None,
'label': 'From PR Date',
'modified': '2011-04-27 09:36:36',
'modified_by': 'Administrator',
'name': 'FL01747',
'no_copy': None,
'oldfieldname': None,
'oldfieldtype': None,
'options': None,
'owner': 'wasim@webnotestech.com',
'parent': 'Landed Cost Wizard',
'parentfield': 'fields',
'parenttype': 'DocType',
'permlevel': 0,
'print_hide': None,
'report_hide': None,
'reqd': 1,
'search_index': None,
'trigger': None,
'width': None
},
{
'allow_on_submit': None,
'colour': None,
'creation': '2010-08-08 17:09:07',
'default': None,
'depends_on': None,
'description': None,
'docstatus': 0,
'doctype': 'DocField',
'fieldname': 'to_pr_date',
'fieldtype': 'Date',
'hidden': None,
'icon': None,
'idx': 3,
'in_filter': None,
'label': 'To PR Date',
'modified': '2011-04-27 09:36:36',
'modified_by': 'Administrator',
'name': 'FL01748',
'no_copy': None,
'oldfieldname': None,
'oldfieldtype': None,
'options': None,
'owner': 'wasim@webnotestech.com',
'parent': 'Landed Cost Wizard',
'parentfield': 'fields',
'parenttype': 'DocType',
'permlevel': 0,
'print_hide': None,
'report_hide': None,
'reqd': 1,
'search_index': None,
'trigger': None,
'width': None
},
{
'allow_on_submit': None,
'colour': None,
'creation': '2010-08-08 17:09:07',
'default': None,
'depends_on': None,
'description': None,
'docstatus': 0,
'doctype': 'DocField',
'fieldname': 'currency',
'fieldtype': 'Select',
'hidden': None,
'icon': None,
'idx': 4,
'in_filter': None,
'label': 'Currency',
'modified': '2011-04-27 09:36:36',
'modified_by': 'Administrator',
'name': 'FL01749',
'no_copy': None,
'oldfieldname': None,
'oldfieldtype': None,
'options': 'link:Currency',
'owner': 'wasim@webnotestech.com',
'parent': 'Landed Cost Wizard',
'parentfield': 'fields',
'parenttype': 'DocType',
'permlevel': 0,
'print_hide': None,
'report_hide': None,
'reqd': 1,
'search_index': None,
'trigger': None,
'width': None
},
{
'allow_on_submit': None,
'colour': None,
'creation': '2010-08-08 17:09:07',
'default': None,
'depends_on': None,
'description': None,
'docstatus': 0,
'doctype': 'DocField',
'fieldname': None,
'fieldtype': 'Button',
'hidden': None,
'icon': None,
'idx': 5,
'in_filter': None,
'label': 'Get Purchase Receipt',
'modified': '2011-04-27 09:36:36',
'modified_by': 'Administrator',
'name': 'FL01750',
'no_copy': None,
'oldfieldname': None,
'oldfieldtype': None,
'options': 'get_purchase_receipts',
'owner': 'wasim@webnotestech.com',
'parent': 'Landed Cost Wizard',
'parentfield': 'fields',
'parenttype': 'DocType',
'permlevel': 0,
'print_hide': None,
'report_hide': None,
'reqd': None,
'search_index': None,
'trigger': None,
'width': None
},
{
'allow_on_submit': None,
'colour': None,
'creation': '2010-08-08 17:09:07',
'default': None,
'depends_on': None,
'description': None,
'docstatus': 0,
'doctype': 'DocField',
'fieldname': None,
'fieldtype': 'Section Break',
'hidden': None,
'icon': None,
'idx': 6,
'in_filter': None,
'label': 'Purchase Receipts',
'modified': '2011-04-27 09:36:36',
'modified_by': 'Administrator',
'name': 'FL01751',
'no_copy': None,
'oldfieldname': None,
'oldfieldtype': None,
'options': 'Simple',
'owner': 'wasim@webnotestech.com',
'parent': 'Landed Cost Wizard',
'parentfield': 'fields',
'parenttype': 'DocType',
'permlevel': 0,
'print_hide': None,
'report_hide': None,
'reqd': None,
'search_index': None,
'trigger': None,
'width': None
},
{
'allow_on_submit': None,
'colour': 'White:FFF',
'creation': '2010-08-08 17:09:07',
'default': None,
'depends_on': None,
'description': 'The landed costs will be distributed among items in these Purchase Receipts',
'docstatus': 0,
'doctype': 'DocField',
'fieldname': 'lc_pr_details',
'fieldtype': 'Table',
'hidden': None,
'icon': None,
'idx': 7,
'in_filter': None,
'label': 'LC PR Details',
'modified': '2011-04-27 09:36:36',
'modified_by': 'Administrator',
'name': 'FL01752',
'no_copy': None,
'oldfieldname': None,
'oldfieldtype': None,
'options': 'LC PR Detail',
'owner': 'wasim@webnotestech.com',
'parent': 'Landed Cost Wizard',
'parentfield': 'fields',
'parenttype': 'DocType',
'permlevel': 0,
'print_hide': None,
'report_hide': None,
'reqd': None,
'search_index': None,
'trigger': None,
'width': None
},
{
'allow_on_submit': None,
'colour': None,
'creation': '2010-08-08 17:09:07',
'default': None,
'depends_on': None,
'description': None,
'docstatus': 0,
'doctype': 'DocField',
'fieldname': None,
'fieldtype': 'Section Break',
'hidden': None,
'icon': None,
'idx': 8,
'in_filter': None,
'label': 'Landed Cost Detail',
'modified': '2011-04-27 09:36:36',
'modified_by': 'Administrator',
'name': 'FL01753',
'no_copy': None,
'oldfieldname': None,
'oldfieldtype': None,
'options': 'Simple',
'owner': 'wasim@webnotestech.com',
'parent': 'Landed Cost Wizard',
'parentfield': 'fields',
'parenttype': 'DocType',
'permlevel': 0,
'print_hide': None,
'report_hide': None,
'reqd': None,
'search_index': None,
'trigger': None,
'width': None
},
{
'allow_on_submit': None,
'colour': None,
'creation': '2010-08-08 17:09:07',
'default': None,
'depends_on': None,
'description': None,
'docstatus': 0,
'doctype': 'DocField',
'fieldname': 'landed_cost',
'fieldtype': 'Link',
'hidden': None,
'icon': None,
'idx': 9,
'in_filter': None,
'label': 'Select Landed Cost Details Master',
'modified': '2011-04-27 09:36:36',
'modified_by': 'Administrator',
'name': 'FL01754',
'no_copy': None,
'oldfieldname': None,
'oldfieldtype': None,
'options': 'Landed Cost Master',
'owner': 'Administrator',
'parent': 'Landed Cost Wizard',
'parentfield': 'fields',
'parenttype': 'DocType',
'permlevel': 0,
'print_hide': None,
'report_hide': None,
'reqd': None,
'search_index': None,
'trigger': None,
'width': None
},
{
'allow_on_submit': None,
'colour': 'White:FFF',
'creation': '2010-08-08 17:09:07',
'default': None,
'depends_on': None,
'description': None,
'docstatus': 0,
'doctype': 'DocField',
'fieldname': None,
'fieldtype': 'Button',
'hidden': None,
'icon': None,
'idx': 10,
'in_filter': None,
'label': 'Get Details',
'modified': '2011-04-27 09:36:36',
'modified_by': 'Administrator',
'name': 'FL01755',
'no_copy': None,
'oldfieldname': None,
'oldfieldtype': None,
'options': 'get_landed_cost_master_details',
'owner': 'Administrator',
'parent': 'Landed Cost Wizard',
'parentfield': 'fields',
'parenttype': 'DocType',
'permlevel': 0,
'print_hide': None,
'report_hide': None,
'reqd': None,
'search_index': None,
'trigger': None,
'width': None
},
{
'allow_on_submit': None,
'colour': 'White:FFF',
'creation': '2010-08-08 17:09:07',
'default': None,
'depends_on': None,
'description': 'Additional costs to be loaded to item valuation',
'docstatus': 0,
'doctype': 'DocField',
'fieldname': 'landed_cost_details',
'fieldtype': 'Table',
'hidden': None,
'icon': None,
'idx': 11,
'in_filter': None,
'label': 'Landed Cost Details',
'modified': '2011-04-27 09:36:36',
'modified_by': 'Administrator',
'name': 'FL01756',
'no_copy': None,
'oldfieldname': None,
'oldfieldtype': None,
'options': 'Landed Cost Detail',
'owner': 'wasim@webnotestech.com',
'parent': 'Landed Cost Wizard',
'parentfield': 'fields',
'parenttype': 'DocType',
'permlevel': 0,
'print_hide': None,
'report_hide': None,
'reqd': None,
'search_index': None,
'trigger': None,
'width': None
},
{
'allow_on_submit': None,
'colour': None,
'creation': '2010-08-08 17:09:07',
'default': None,
'depends_on': None,
'description': None,
'docstatus': 0,
'doctype': 'DocField',
'fieldname': None,
'fieldtype': 'Button',
'hidden': None,
'icon': None,
'idx': 12,
'in_filter': None,
'label': 'Update PR',
'modified': '2011-04-27 09:36:36',
'modified_by': 'Administrator',
'name': 'FL01757',
'no_copy': None,
'oldfieldname': None,
'oldfieldtype': None,
'options': 'update_pr_lc_se',
'owner': 'wasim@webnotestech.com',
'parent': 'Landed Cost Wizard',
'parentfield': 'fields',
'parenttype': 'DocType',
'permlevel': 0,
'print_hide': None,
'report_hide': None,
'reqd': None,
'search_index': None,
'trigger': None,
'width': None
}
]

View File

@@ -0,0 +1,285 @@
cur_frm.cscript.tname = "Purchase Receipt Detail";
cur_frm.cscript.fname = "purchase_receipt_details";
cur_frm.cscript.other_fname = "purchase_tax_details";
$import(Purchase Common)
$import(Purchase Other Charges)
$import(SMS Control)
//========================== On Load ================================================================
cur_frm.cscript.onload = function(doc, cdt, cdn) {
if(!doc.fiscal_year && doc.__islocal){ set_default_values(doc);}
if (!doc.posting_date) doc.posting_date = dateutil.obj_to_str(new Date());
if (!doc.transaction_date) doc.transaction_date = dateutil.obj_to_str(new Date());
if (!doc.status) doc.status = 'Draft';
if(doc.__islocal){
cur_frm.cscript.get_default_schedule_date(doc);
}
if(doc.__islocal){
hide_field(['supplier_name','supplier_address','contact_person','address_display','contact_display','contact_mobile','contact_email']);
}
if(doc.supplier) unhide_field(['supplier_name','supplier_address','contact_person','address_display','contact_display','contact_mobile','contact_email']);
}
//========================== Refresh ===============================================================
cur_frm.cscript.refresh = function(doc, cdt, cdn) {
// Unhide Fields in Next Steps
// ---------------------------------
cur_frm.clear_custom_buttons();
if(doc.docstatus == 1){
var ch = getchildren('Purchase Receipt Detail',doc.name,'purchase_receipt_details');
allow_billing = 0;
for(var i in ch){
if(ch[i].qty > ch[i].billed_qty) allow_billing = 1;
}
cur_frm.add_custom_button('Make Purchase Invoice', cur_frm.cscript['Make Purchase Invoice']);
cur_frm.add_custom_button('Send SMS', cur_frm.cscript['Send SMS']);
}
else{
hide_field(['Repair Purchase Receipt']);
}
}
//Supplier
cur_frm.cscript.supplier = function(doc,dt,dn) {
if(doc.supplier) get_server_fields('get_default_supplier_address', JSON.stringify({supplier: doc.supplier}),'', doc, dt, dn, 1);
if(doc.supplier) unhide_field(['supplier_name','supplier_address','contact_person','address_display','contact_display','contact_mobile','contact_email']);
}
cur_frm.cscript.supplier_address = cur_frm.cscript.contact_person = function(doc,dt,dn) {
if(doc.supplier) get_server_fields('get_supplier_address', JSON.stringify({supplier: doc.supplier, address: doc.supplier_address, contact: doc.contact_person}),'', doc, dt, dn, 1);
}
cur_frm.fields_dict['supplier_address'].get_query = function(doc, cdt, cdn) {
return 'SELECT name,address_line1,city FROM tabAddress WHERE supplier = "'+ doc.supplier +'" AND docstatus != 2 AND name LIKE "%s" ORDER BY name ASC LIMIT 50';
}
cur_frm.fields_dict['contact_person'].get_query = function(doc, cdt, cdn) {
return 'SELECT name,CONCAT(first_name," ",ifnull(last_name,"")) As FullName,department,designation FROM tabContact WHERE supplier = "'+ doc.supplier +'" AND docstatus != 2 AND name LIKE "%s" ORDER BY name ASC LIMIT 50';
}
cur_frm.fields_dict.supplier_address.on_new = function(dn) {
locals['Address'][dn].supplier = locals[cur_frm.doctype][cur_frm.docname].supplier;
locals['Address'][dn].supplier_name = locals[cur_frm.doctype][cur_frm.docname].supplier_name;
}
cur_frm.fields_dict.contact_person.on_new = function(dn) {
locals['Contact'][dn].supplier = locals[cur_frm.doctype][cur_frm.docname].supplier;
locals['Contact'][dn].supplier_name = locals[cur_frm.doctype][cur_frm.docname].supplier_name;
}
// Get Purchase Order Button
// -----------------
cur_frm.cscript['Pull Purchase Order Details'] = function(doc, dt, dn) {
var callback = function(r,rt) {
unhide_field(['supplier_address','contact_person','supplier_name','address_display','contact_display','contact_mobile','contact_email']);
refresh_many(['supplier','supplier_address','contact_person','supplier_name','address_display','contact_display','contact_mobile','contact_email','purchase_receipt_details']);
}
get_server_fields('get_po_details','','',doc, dt, dn,1,callback);
}
//================ create new contact ============================================================================
cur_frm.cscript.new_contact = function(){
tn = createLocal('Contact');
locals['Contact'][tn].is_supplier = 1;
if(doc.supplier) locals['Contact'][tn].supplier = doc.supplier;
loaddoc('Contact', tn);
}
//======================= posting date =============================
cur_frm.cscript.transaction_date = function(doc,cdt,cdn){
if(doc.__islocal){
cur_frm.cscript.get_default_schedule_date(doc);
}
}
// ***************** Get project name *****************
cur_frm.fields_dict['project_name'].get_query = function(doc, cdt, cdn) {
return 'SELECT `tabProject`.name FROM `tabProject` WHERE `tabProject`.status = "Open" AND `tabProject`.name LIKE "%s" ORDER BY `tabProject`.name ASC LIMIT 50';
}
//========================= Overloaded query for link batch_no =============================================================
cur_frm.fields_dict['purchase_receipt_details'].grid.get_field('batch_no').get_query= function(doc, cdt, cdn) {
var d = locals[cdt][cdn];
if(d.item_code){
return "SELECT tabBatch.name, tabBatch.description FROM tabBatch WHERE tabBatch.docstatus != 2 AND tabBatch.item = '"+ d.item_code +"' AND `tabBatch`.`name` like '%s' ORDER BY `tabBatch`.`name` DESC LIMIT 50"
}
else{
alert("Please enter Item Code.");
}
}
cur_frm.cscript.select_print_heading = function(doc,cdt,cdn){
if(doc.select_print_heading){
// print heading
cur_frm.pformat.print_heading = doc.select_print_heading;
}
else
cur_frm.pformat.print_heading = "Purchase Receipt";
}
// ***************** Get Print Heading *****************
cur_frm.fields_dict['select_print_heading'].get_query = function(doc, cdt, cdn) {
return 'SELECT `tabPrint Heading`.name FROM `tabPrint Heading` WHERE `tabPrint Heading`.docstatus !=2 AND `tabPrint Heading`.name LIKE "%s" ORDER BY `tabPrint Heading`.name ASC LIMIT 50';
}
//========================= Received Qty =============================================================
cur_frm.cscript.received_qty = function(doc, cdt, cdn) {
var d = locals[cdt][cdn];
ret = {
'qty' : 0,
'stock_qty': 0,
'rejected_qty' : 0
}
set_multiple('Purchase Receipt Detail', cdn, ret, 'purchase_receipt_details');
cur_frm.cscript.calc_amount(doc, 2);
}
//======================== Qty (Accepted Qty) =========================================================
cur_frm.cscript.qty = function(doc, cdt, cdn) {
var d = locals[cdt][cdn];
// Step 1 :=> Check If Qty > Received Qty
if (flt(d.qty) > flt(d.received_qty)) {
alert("Accepted Qty cannot be greater than Received Qty")
ret = {
'qty' : 0,
'stock_qty': 0,
'rejected_qty' : 0
}
// => Set Qty = 0 and rejected_qty = 0
set_multiple('Purchase Receipt Detail', cdn, ret, 'purchase_receipt_details');
cur_frm.cscript.calc_amount(doc, 2);
// => Return
return
}
// Step 2 :=> Check IF Qty <= REceived Qty
else {
ret = {
'rejected_qty':flt(d.received_qty) - flt(d.qty)
}
// => Set Rejected Qty = Received Qty - Qty
set_multiple('Purchase Receipt Detail', cdn, ret, 'purchase_receipt_details');
// => Calculate Amount
cur_frm.cscript.calc_amount(doc, 2);
cur_frm.cscript.update_stock_qty(doc,cdt,cdn);
}
}
//======================== Rejected Qty =========================================================
cur_frm.cscript.rejected_qty = function(doc, cdt, cdn) {
var d = locals[cdt][cdn];
// Step 1 :=> Check If Rejected Qty > Received Qty
if (flt(d.rejected_qty) > flt(d.received_qty)) {
alert("Rejected Qty cannot be greater than Received Qty")
ret = {
'qty' : 0,
'stock_qty': 0,
'rejected_qty' : 0
}
// => Set Qty = 0 and rejected_qty = 0
set_multiple('Purchase Receipt Detail', cdn, ret, 'purchase_receipt_details');
cur_frm.cscript.calc_amount(doc, 2);
// => Return
return
}
// Step 2 :=> Check IF Rejected Qty <= REceived Qty
else {
ret = {
'qty':flt(d.received_qty) - flt(d.rejected_qty)
}
// => Set Qty = Received Qty - Rejected Qty
set_multiple('Purchase Receipt Detail', cdn, ret, 'purchase_receipt_details');
// Calculate Amount
cur_frm.cscript.calc_amount(doc, 2);
cur_frm.cscript.update_stock_qty(doc,cdt,cdn);
}
}
//================================= Purchase Order No Get Query ====================================
cur_frm.fields_dict['purchase_order_no'].get_query = function(doc) {
if (doc.supplier)
return 'SELECT DISTINCT `tabPurchase Order`.`name` FROM `tabPurchase Order` WHERE `tabPurchase Order`.`supplier` = "' +doc.supplier + '" and`tabPurchase Order`.`docstatus` = 1 and `tabPurchase Order`.`status` != "Stopped" and ifnull(`tabPurchase Order`.`per_received`, 0) < 100 and `tabPurchase Order`.`currency` = ifnull("' +doc.currency+ '","") and `tabPurchase Order`.company = "'+ doc.company +'" and `tabPurchase Order`.%(key)s LIKE "%s" ORDER BY `tabPurchase Order`.`name` DESC LIMIT 50';
else
return 'SELECT DISTINCT `tabPurchase Order`.`name` FROM `tabPurchase Order` WHERE `tabPurchase Order`.`docstatus` = 1 and `tabPurchase Order`.`company` = "'+ doc.company +'" and `tabPurchase Order`.`status` != "Stopped" and ifnull(`tabPurchase Order`.`per_received`, 0) < 100 and `tabPurchase Order`.%(key)s LIKE "%s" ORDER BY `tabPurchase Order`.`name` DESC LIMIT 50';
}
// QA INspection report get_query
//---------------------------------
cur_frm.fields_dict.purchase_receipt_details.grid.get_field("qa_no").get_query = function(doc) {
return 'SELECT `tabQA Inspection Report`.name FROM `tabQA Inspection Report` WHERE `tabQA Inspection Report`.docstatus = 1 AND `tabQA Inspection Report`.%(key)s LIKE "%s"';
}
// On Button Click Functions
// ------------------------------------------------------------------------------
// ================================ Make Purchase Invoice ==========================================
cur_frm.cscript['Make Purchase Invoice'] = function() {
n = createLocal('Payable Voucher');
$c('dt_map', args={
'docs':compress_doclist([locals['Payable Voucher'][n]]),
'from_doctype': cur_frm.doc.doctype,
'to_doctype':'Payable Voucher',
'from_docname': cur_frm.doc.name,
'from_to_list':"[['Purchase Receipt','Payable Voucher'],['Purchase Receipt Detail','PV Detail']]"
}, function(r,rt) {
loaddoc('Payable Voucher', n);
}
);
}
//****************** For print sales order no and date*************************
cur_frm.pformat.purchase_order_no = function(doc, cdt, cdn){
//function to make row of table
var make_row = function(title,val1, val2, bold){
var bstart = '<b>'; var bend = '</b>';
return '<tr><td style="width:39%;">'+(bold?bstart:'')+title+(bold?bend:'')+'</td>'
+'<td style="width:61%;text-align:left;">'+val1+(val2?' ('+dateutil.str_to_user(val2)+')':'')+'</td>'
+'</tr>'
}
out ='';
var cl = getchildren('Purchase Receipt Detail',doc.name,'purchase_receipt_details');
// outer table
var out='<div><table class="noborder" style="width:100%"><tr><td style="width: 50%"></td><td>';
// main table
out +='<table class="noborder" style="width:100%">';
// add rows
if(cl.length){
prevdoc_list = new Array();
for(var i=0;i<cl.length;i++){
if(cl[i].prevdoc_doctype == 'Purchase Order' && cl[i].prevdoc_docname && prevdoc_list.indexOf(cl[i].prevdoc_docname) == -1) {
prevdoc_list.push(cl[i].prevdoc_docname);
if(prevdoc_list.length ==1)
out += make_row(cl[i].prevdoc_doctype, cl[i].prevdoc_docname, cl[i].prevdoc_date,0);
else
out += make_row('', cl[i].prevdoc_docname, cl[i].prevdoc_date,0);
}
}
}
out +='</table></td></tr></table></div>';
return out;
}

View File

@@ -0,0 +1,434 @@
# Please edit this list and import only required elements
import webnotes
from webnotes.utils import add_days, add_months, add_years, cint, cstr, date_diff, default_fields, flt, fmt_money, formatdate, generate_hash, getTraceback, get_defaults, get_first_day, get_last_day, getdate, has_common, month_name, now, nowdate, replace_newlines, sendmail, set_default, str_esc_quote, user_format, validate_email_add
from webnotes.model import db_exists
from webnotes.model.doc import Document, addchild, removechild, getchildren, make_autoname, SuperDocType
from webnotes.model.doclist import getlist, copy_doclist
from webnotes.model.code import get_obj, get_server_obj, run_server_obj, updatedb, check_syntax
from webnotes import session, form, is_testing, msgprint, errprint
set = webnotes.conn.set
sql = webnotes.conn.sql
get_value = webnotes.conn.get_value
in_transaction = webnotes.conn.in_transaction
convert_to_lists = webnotes.conn.convert_to_lists
# -----------------------------------------------------------------------------------------
from utilities.transaction_base import TransactionBase
class DocType(TransactionBase):
def __init__(self, doc, doclist=[]):
self.doc = doc
self.doclist = doclist
self.defaults = get_defaults()
self.tname = 'Purchase Receipt Detail'
self.fname = 'purchase_receipt_details'
self.count = 0
# Autoname
# ---------
def autoname(self):
self.doc.name = make_autoname(self.doc.naming_series+'.#####')
# Client Trigger Functions
#----------------------------------------------------------------------------------------------------
def get_default_schedule_date(self):
get_obj(dt = 'Purchase Common').get_default_schedule_date(self)
#-----------------Validation For Fiscal Year------------------------
def validate_fiscal_year(self):
get_obj(dt = 'Purchase Common').validate_fiscal_year(self.doc.fiscal_year,self.doc.transaction_date,'Transaction Date')
# Get Supplier Details
#def get_supplier_details(self, name = ''):
# return cstr(get_obj(dt='Purchase Common').get_supplier_details(name))
# Get Item Details
def get_item_details(self, arg = ''):
return cstr(get_obj(dt='Purchase Common').get_item_details(self,arg))
# Get UOM Details
def get_uom_details(self, arg = ''):
return cstr(get_obj(dt='Purchase Common').get_uom_details(arg))
# GET TERMS & CONDITIONS
# =====================================================================================
def get_tc_details(self):
return get_obj('Purchase Common').get_tc_details(self)
# get available qty at warehouse
def get_bin_details(self, arg = ''):
return cstr(get_obj(dt='Purchase Common').get_bin_details(arg))
# Pull Purchase Order
def get_po_details(self):
self.validate_prev_docname()
get_obj('DocType Mapper', 'Purchase Order-Purchase Receipt').dt_map('Purchase Order', 'Purchase Receipt', self.doc.purchase_order_no, self.doc, self.doclist, "[['Purchase Order','Purchase Receipt'],['PO Detail', 'Purchase Receipt Detail'],['Purchase Tax Detail','Purchase Tax Detail']]")
# validate if PO has been pulled twice
def validate_prev_docname(self):
for d in getlist(self.doclist, 'purchase_receipt_details'):
if self.doc.purchase_order_no and d.prevdoc_docname and self.doc.purchase_order_no == d.prevdoc_docname:
msgprint(cstr(self.doc.purchase_order_no) + " Purchase Order details have already been pulled. ")
raise Exception
# validation
#-------------------------------------------------------------------------------------------------------------
# validate accepted and rejected qty
def validate_accepted_rejected_qty(self):
for d in getlist(self.doclist, "purchase_receipt_details"):
# If Reject Qty than Rejected warehouse is mandatory
if flt(d.rejected_qty) and (not self.doc.rejected_warehouse):
msgprint("Rejected Warehouse is necessary if there are rejections. See 'Receipt Items'")
raise Exception
# Check Received Qty = Accepted Qty + Rejected Qty
if ((flt(d.qty) + flt(d.rejected_qty)) != flt(d.received_qty)):
msgprint("Sum of Accepted Qty and Rejected Qty must be equal to Received quantity. Error for Item: " + cstr(d.item_code))
raise Exception
# update valuation rate
def update_valuation_rate(self):
total_b_cost = flt(self.doc.buying_cost_transport) + flt(self.doc.buying_cost_taxes) + flt(self.doc.buying_cost_other)
for d in getlist(self.doclist, 'purchase_receipt_details'):
if flt(self.doc.net_total) and flt(d.qty):
#d.valuation_rate = (flt(d.purchase_rate) + ((flt(d.amount) * (total_b_cost)) / (self.doc.net_total * flt(d.qty))) + (flt(d.rm_supp_cost) / flt(d.qty))) / flt(d.conversion_factor)
d.valuation_rate = (flt(d.purchase_rate) + ((flt(d.amount) * (total_b_cost)) / (self.doc.net_total * flt(d.qty))) + (flt(d.rm_supp_cost) / flt(d.qty)) + (flt(d.item_tax_amount)/flt(d.qty))) / flt(d.conversion_factor)
# Check for Stopped status
def check_for_stopped_status(self, pc_obj):
check_list =[]
for d in getlist(self.doclist, 'purchase_receipt_details'):
if d.fields.has_key('prevdoc_docname') and d.prevdoc_docname and d.prevdoc_docname not in check_list:
check_list.append(d.prevdoc_docname)
pc_obj.check_for_stopped_status( d.prevdoc_doctype, d.prevdoc_docname)
#check in manage account if purchase order required or not.
# ====================================================================================
def po_required(self):
res = sql("select value from `tabSingles` where doctype = 'Manage Account' and field = 'po_required'")
if res and res[0][0]== 'Yes':
for d in getlist(self.doclist,'purchase_receipt_details'):
if not d.prevdoc_docname:
msgprint("Purchse Order No. required against item %s"%d.item_code)
raise Exception
# validate
def validate(self):
self.po_required()
self.validate_fiscal_year()
set(self.doc, 'status', 'Draft') # set status as "Draft"
self.validate_accepted_rejected_qty()
self.validate_inspection() # Validate Inspection
get_obj('Stock Ledger').validate_serial_no(self, 'purchase_receipt_details')
pc_obj = get_obj(dt='Purchase Common')
pc_obj.validate_for_items(self)
pc_obj.validate_mandatory(self)
pc_obj.validate_conversion_rate(self)
pc_obj.get_prevdoc_date(self)
pc_obj.validate_reference_value(self)
self.check_for_stopped_status(pc_obj)
# get total in words
self.doc.in_words = pc_obj.get_total_in_words(get_defaults().get('currency') or 'INR', self.doc.grand_total)
self.doc.in_words_import = pc_obj.get_total_in_words(self.doc.currency, self.doc.grand_total_import)
# update valuation rate
self.update_valuation_rate()
# On Update
# ----------------------------------------------------------------------------------------------------
def on_update(self):
if self.doc.rejected_warehouse:
for d in getlist(self.doclist,'purchase_receipt_details'):
d.rejected_warehouse = self.doc.rejected_warehouse
self.update_rw_material_detail()
get_obj('Stock Ledger').scrub_serial_nos(self)
# On Submit
# -----------------------------------------------------------------------------------------------------
# Update Stock
def update_stock(self, is_submit):
pc_obj = get_obj('Purchase Common')
self.values = []
for d in getlist(self.doclist, 'purchase_receipt_details'):
# Check if is_stock_item == 'Yes'
if sql("select is_stock_item from tabItem where name=%s", d.item_code)[0][0]=='Yes':
ord_qty = 0
pr_qty = flt(d.qty) * flt(d.conversion_factor)
# Check If Prevdoc Doctype is Purchase Order
if cstr(d.prevdoc_doctype) == 'Purchase Order':
# get qty and pending_qty of prevdoc
curr_ref_qty = pc_obj.get_qty( d.doctype, 'prevdoc_detail_docname', d.prevdoc_detail_docname, 'PO Detail', 'Purchase Order - Purchase Receipt', self.doc.name)
max_qty, qty, curr_qty = flt(curr_ref_qty.split('~~~')[1]), flt(curr_ref_qty.split('~~~')[0]), 0
if flt(qty) + flt(pr_qty) > flt(max_qty):
curr_qty = (flt(max_qty) - flt(qty)) * flt(d.conversion_factor)
else:
curr_qty = flt(pr_qty)
ord_qty = -flt(curr_qty)
# update order qty in bin
bin = get_obj('Warehouse', d.warehouse).update_bin(0, 0, (is_submit and 1 or -1) * flt(ord_qty), 0, 0, d.item_code, self.doc.transaction_date)
# UPDATE actual qty to warehouse by pr_qty
self.make_sl_entry(d, d.warehouse, flt(pr_qty), d.valuation_rate, is_submit)
# UPDATE actual to rejected warehouse by rejected qty
if flt(d.rejected_qty) > 0:
self.make_sl_entry(d, self.doc.rejected_warehouse, flt(d.rejected_qty) * flt(d.conversion_factor), d.valuation_rate, is_submit)
self.bk_flush_supp_wh(is_submit)
if self.values:
get_obj('Stock Ledger', 'Stock Ledger').update_stock(self.values)
# make Stock Entry
def make_sl_entry(self, d, wh, qty, in_value, is_submit):
self.values.append({
'item_code' : d.fields.has_key('item_code') and d.item_code or d.rm_item_code,
'warehouse' : wh,
'transaction_date' : self.doc.transaction_date,
'posting_date' : self.doc.posting_date,
'posting_time' : self.doc.posting_time,
'voucher_type' : 'Purchase Receipt',
'voucher_no' : self.doc.name,
'voucher_detail_no' : d.name,
'actual_qty' : qty,
'stock_uom' : d.stock_uom,
'incoming_rate' : in_value,
'company' : self.doc.company,
'fiscal_year' : self.doc.fiscal_year,
'is_cancelled' : (is_submit==1) and 'No' or 'Yes',
'batch_no' : d.batch_no,
'serial_no' : d.serial_no
})
def validate_inspection(self):
for d in getlist(self.doclist, 'purchase_receipt_details'): #Enter inspection date for all items that require inspection
ins_reqd = sql("select inspection_required from `tabItem` where name = %s", (d.item_code), as_dict = 1)
ins_reqd = ins_reqd and ins_reqd[0]['inspection_required'] or 'No'
if ins_reqd == 'Yes' and not d.qa_no:
msgprint("Item: " + d.item_code + " requires QA Inspection. Please enter QA No or report to authorized person to create QA Inspection Report")
# Check for Stopped status
def check_for_stopped_status(self, pc_obj):
check_list =[]
for d in getlist(self.doclist, 'purchase_receipt_details'):
if d.fields.has_key('prevdoc_docname') and d.prevdoc_docname and d.prevdoc_docname not in check_list:
check_list.append(d.prevdoc_docname)
pc_obj.check_for_stopped_status( d.prevdoc_doctype, d.prevdoc_docname)
# on submit
def on_submit(self):
# Check for Approving Authority
get_obj('Authorization Control').validate_approving_authority(self.doc.doctype, self.doc.company, self.doc.grand_total)
# Set status as Submitted
set(self.doc,'status', 'Submitted')
pc_obj = get_obj('Purchase Common')
# Update Previous Doc i.e. update pending_qty and Status accordingly
pc_obj.update_prevdoc_detail(self, is_submit = 1)
# Update Serial Record
get_obj('Stock Ledger').update_serial_record(self, 'purchase_receipt_details', is_submit = 1, is_incoming = 1)
# Update Stock
self.update_stock(is_submit = 1)
# Update last purchase rate
pc_obj.update_last_purchase_rate(self, 1)
# on submit notification
get_obj('Notification Control').notify_contact('Purchase Receipt', self.doc.doctype,self.doc.name, self.doc.email_id, self.doc.contact_person)
#On Cancel
#----------------------------------------------------------------------------------------------------
def check_next_docstatus(self):
submit_rv = sql("select t1.name from `tabPayable Voucher` t1,`tabPV Detail` t2 where t1.name = t2.parent and t2.purchase_receipt = '%s' and t1.docstatus = 1" % (self.doc.name))
if submit_rv:
msgprint("Purchase Invoice : " + cstr(self.submit_rv[0][0]) + " has already been submitted !")
raise Exception , "Validation Error."
def on_cancel(self):
pc_obj = get_obj('Purchase Common')
self.check_for_stopped_status(pc_obj)
# 1.Check if Payable Voucher has been submitted against current Purchase Order
# pc_obj.check_docstatus(check = 'Next', doctype = 'Payable Voucher', docname = self.doc.name, detail_doctype = 'PV Detail')
submitted = sql("select t1.name from `tabPayable Voucher` t1,`tabPV Detail` t2 where t1.name = t2.parent and t2.purchase_receipt = '%s' and t1.docstatus = 1" % self.doc.name)
if submitted:
msgprint("Purchase Invoice : " + cstr(submitted[0][0]) + " has already been submitted !")
raise Exception
# 2.Set Status as Cancelled
set(self.doc,'status','Cancelled')
# 3. Cancel Serial No
get_obj('Stock Ledger').update_serial_record(self, 'purchase_receipt_details', is_submit = 0, is_incoming = 1)
# 4.Update Bin
self.update_stock(is_submit = 0)
# 5.Update Indents Pending Qty and accordingly it's Status
pc_obj.update_prevdoc_detail(self, is_submit = 0)
# 6. Update last purchase rate
pc_obj.update_last_purchase_rate(self, 0)
#----------- code for Sub-contracted Items -------------------
#--------check for sub-contracted items and accordingly update PR raw material detail table--------
def update_rw_material_detail(self):
for d in getlist(self.doclist,'purchase_receipt_details'):
item_det = sql("select is_sub_contracted_item, is_purchase_item from `tabItem` where name = '%s'"%(d.item_code))
if item_det[0][0] == 'Yes':
if item_det[0][1] == 'Yes':
if not self.doc.is_subcontracted:
msgprint("Please enter whether purchase receipt to be made for subcontracting or for purchase in 'Is Subcontracted' field .")
raise Exception
if self.doc.is_subcontracted == 'Yes':
if not self.doc.supplier_warehouse:
msgprint("Please Enter Supplier Warehouse for subcontracted Items")
raise Exception
self.add_bom(d)
else:
self.doc.clear_table(self.doclist,'pr_raw_material_details',1)
self.doc.save()
elif item_det[0][1] == 'No':
if not self.doc.supplier_warehouse:
msgprint("Please Enter Supplier Warehouse for subcontracted Items")
raise Exception
self.add_bom(d)
self.delete_irrelevant_raw_material()
#---------------calculate amt in PR Raw Material Detail-------------
self.calculate_amount(d)
def add_bom(self, d):
#----- fetching default bom from Bill of Materials instead of Item Master --
bom_det = sql("select t1.item, t2.item_code, t2.qty_consumed_per_unit, t2.moving_avg_rate, t2.value_as_per_mar, t2.stock_uom, t2.name, t2.description from `tabBill Of Materials` t1, `tabBOM Material` t2 where t2.parent = t1.name and t1.item = '%s' and ifnull(t1.is_default,0) = 1 and t1.docstatus = 1 and t2.docstatus =1" % d.item_code)
if not bom_det:
msgprint("No default BOM exists for item: %s" % d.item_code)
raise Exception
else:
#-------------- add child function--------------------
chgd_rqd_qty = []
for i in bom_det:
if i and not sql("select name from `tabPR Raw Material Detail` where reference_name = '%s' and bom_detail_no = '%s' and parent = '%s' " %(d.name, i[6], self.doc.name)):
rm_child = addchild(self.doc, 'pr_raw_material_details', 'PR Raw Material Detail', 1, self.doclist)
rm_child.reference_name = d.name
rm_child.bom_detail_no = i and i[6] or ''
rm_child.main_item_code = i and i[0] or ''
rm_child.rm_item_code = i and i[1] or ''
rm_child.description = i and i[7] or ''
rm_child.stock_uom = i and i[5] or ''
rm_child.rate = i and flt(i[3]) or flt(i[4])
rm_child.conversion_factor = d.conversion_factor
rm_child.required_qty = flt(i and flt(i[2]) or 0) * flt(d.qty) * flt(d.conversion_factor)
rm_child.consumed_qty = flt(i and flt(i[2]) or 0) * flt(d.qty) * flt(d.conversion_factor)
rm_child.amount = flt(flt(rm_child.consumed_qty)*flt(rm_child.rate))
rm_child.save()
chgd_rqd_qty.append(cstr(i[1]))
else:
act_qty = flt(i and flt(i[2]) or 0) * flt(d.qty) * flt(d.conversion_factor)
for pr_rmd in getlist(self.doclist, 'pr_raw_material_details'):
if i and i[6] == pr_rmd.bom_detail_no and (flt(act_qty) != flt(pr_rmd.required_qty) or i[1] != pr_rmd.rm_item_code or i[7] != pr_rmd.description):
chgd_rqd_qty.append(cstr(i[1]))
pr_rmd.main_item_code = i[0]
pr_rmd.rm_item_code = i[1]
pr_rmd.description = i[7]
pr_rmd.stock_uom = i[5]
pr_rmd.required_qty = flt(act_qty)
pr_rmd.consumed_qty = flt(act_qty)
pr_rmd.rate = i and flt(i[3]) or flt(i[4])
pr_rmd.amount = flt(flt(pr_rmd.consumed_qty)*flt(pr_rmd.rate))
pr_rmd.save()
if chgd_rqd_qty:
msgprint("Please check consumed quantity for Raw Material Item Code: '%s'in Raw materials Detail Table" % ((len(chgd_rqd_qty) > 1 and ','.join(chgd_rqd_qty[:-1]) +' and ' + cstr(chgd_rqd_qty[-1:][0]) ) or cstr(chgd_rqd_qty[0])))
# Delete irrelevant raw material from PR Raw material details
#--------------------------------------------------------------
def delete_irrelevant_raw_material(self):
for d in getlist(self.doclist,'pr_raw_material_details'):
if not sql("select name from `tabPurchase Receipt Detail` where name = '%s' and parent = '%s' and item_code = '%s'" % (d.reference_name, self.doc.name, d.main_item_code)):
d.parent = 'old_par:'+self.doc.name
d.save()
def calculate_amount(self, d):
amt = 0
for i in getlist(self.doclist,'pr_raw_material_details'):
if(i.reference_name == d.name):
#if i.consumed_qty == 0:
# msgprint("consumed qty cannot be 0. Please Enter consumed qty ")
#raise Exception
i.amount = flt(i.consumed_qty)* flt(i.rate)
amt += i.amount
d.rm_supp_cost = amt
d.save()
# --------------- Back Flush function called on submit and on cancel from update stock
def bk_flush_supp_wh(self, is_submit):
for d in getlist(self.doclist, 'pr_raw_material_details'):
#--------- -ve quantity is passed as raw material qty has to be decreased when PR is submitted and it has to be increased when PR is cancelled
consumed_qty = - flt(d.consumed_qty)
self.make_sl_entry(d, self.doc.supplier_warehouse, flt(consumed_qty), 0, is_submit)
# get current_stock
# ----------------
def get_current_stock(self):
for d in getlist(self.doclist, 'pr_raw_material_details'):
if self.doc.supplier_warehouse:
bin = sql("select actual_qty from `tabBin` where item_code = %s and warehouse = %s", (d.rm_item_code, self.doc.supplier_warehouse), as_dict = 1)
d.current_stock = bin and flt(bin[0]['actual_qty']) or 0
# OTHER CHARGES TRIGGER FUNCTIONS
# ====================================================================================
# *********** Get Tax rate if account type is TAX ********************
def get_rate(self,arg):
return get_obj('Purchase Common').get_rate(arg,self)
# **** Pull details from other charges master (Get Other Charges) ****
def get_purchase_tax_details(self):
return get_obj('Purchase Common').get_purchase_tax_details(self)
# Repair Purchase Order
# ===========================================
def repair_purchase_receipt(self):
get_obj('Purchase Common').repair_curr_doctype_details(self)

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1 @@
[{'section_style': 'Tray', 'is_transaction_doc': None, 'creation': '2009-03-26 15:17:43', 'search_fields': None, 'module': 'Material Management', 'doctype': 'DocType', 'change_log': None, 'print_outline': '', 'owner': 'Administrator', 'in_dialog': None, 'in_create': 1, 'read_only': 0, 'allow_email': None, 'dt_template': None, 'hide_heading': None, 'issingle': None, 'allow_rename': None, 'smallicon': '', 'allow_attach': None, 'show_in_menu': 0, 'max_attachments': None, 'version': 2, 'menu_index': None, 'docstatus': 0, 'allow_copy': None, 'istable': 1, 'description': None, 'parent': None, 'server_code': None, 'allow_trash': None, 'allow_print': None, 'autoname': 'RFD/.#####', 'client_script_core': None, 'client_string': None, 'use_template': None, 'modified_by': 'Administrator', 'document_type': None, 'name': 'Ref Rate Detail', 'idx': None, 'hide_toolbar': None, 'colour': 'White:FFF', 'client_script': None, 'modified': '2010-09-20 14:06:57', 'server_code_error': ' ', 'name_case': '', 'parenttype': None, 'read_only_onload': None, 'server_code_core': None, 'server_code_compiled': None, 'parent_node': None, 'parentfield': None}, {'no_copy': None, 'oldfieldtype': 'Select', 'creation': '2009-03-26 15:17:43', 'doctype': 'DocField', 'oldfieldname': 'price_list_name', 'owner': 'Administrator', 'reqd': 1, 'in_filter': 1, 'print_hide': None, 'modified_by': 'Administrator', 'label': 'Price List Name', 'width': None, 'trigger': None, 'depends_on': None, 'docstatus': 0, 'hidden': None, 'permlevel': 0, 'description': None, 'parent': 'Ref Rate Detail', 'search_index': 1, 'allow_on_submit': None, 'icon': None, 'name': 'FL01475', 'idx': 1, 'default': '', 'colour': None, 'modified': '2010-03-31 10:16:36', 'parenttype': 'DocType', 'fieldname': 'price_list_name', 'fieldtype': 'Select', 'options': 'link:Price List', 'report_hide': None, 'parentfield': 'fields'}, {'no_copy': None, 'oldfieldtype': 'Currency', 'creation': '2009-03-26 15:17:43', 'doctype': 'DocField', 'oldfieldname': 'ref_rate', 'owner': 'Administrator', 'reqd': 0, 'in_filter': 1, 'print_hide': None, 'modified_by': 'Administrator', 'label': 'Ref Rate', 'width': None, 'trigger': None, 'depends_on': None, 'docstatus': 0, 'hidden': None, 'permlevel': 0, 'description': None, 'parent': 'Ref Rate Detail', 'search_index': 1, 'allow_on_submit': None, 'icon': None, 'name': 'FL01476', 'idx': 2, 'default': None, 'colour': None, 'modified': '2010-03-31 10:16:36', 'parenttype': 'DocType', 'fieldname': 'ref_rate', 'fieldtype': 'Currency', 'options': None, 'report_hide': None, 'parentfield': 'fields'}, {'no_copy': None, 'oldfieldtype': 'Select', 'creation': '2009-04-16 12:40:05', 'doctype': 'DocField', 'oldfieldname': 'ref_currency', 'owner': 'Administrator', 'reqd': 1, 'in_filter': 1, 'print_hide': None, 'modified_by': 'Administrator', 'label': 'Currency', 'width': None, 'trigger': None, 'depends_on': None, 'docstatus': 0, 'hidden': None, 'permlevel': 0, 'description': None, 'parent': 'Ref Rate Detail', 'search_index': 1, 'allow_on_submit': None, 'icon': None, 'name': 'FL01916', 'idx': 3, 'default': None, 'colour': None, 'modified': '2010-03-31 10:16:36', 'parenttype': 'DocType', 'fieldname': 'ref_currency', 'fieldtype': 'Select', 'options': 'link:Currency', 'report_hide': None, 'parentfield': 'fields'}]

View File

@@ -0,0 +1,176 @@
// Onload
//-------------------------------
cur_frm.cscript.onload = function(doc,dt,dn){
if(!doc.return_date) set_multiple(dt,dn,{return_date:get_today()});
doc.delivery_note_no = '';
doc.purchase_receipt_no = '';
doc.sales_invoice_no = '';
doc.return_type ='';
refresh_many(['delivery_note_no', 'sales_invoice_no', 'purchase_receipt_no', 'return_type']);
}
// Link field query
//--------------------------------
cur_frm.fields_dict.delivery_note_no.get_query = function(doc) {
return 'SELECT DISTINCT `tabDelivery Note`.name FROM `tabDelivery Note` WHERE `tabDelivery Note`.docstatus = 1 AND `tabDelivery Note`.%(key)s LIKE "%s" ORDER BY `tabDelivery Note`.name desc LIMIT 50';
}
cur_frm.fields_dict.sales_invoice_no.get_query = function(doc) {
return 'SELECT DISTINCT `tabReceivable Voucher`.name FROM `tabReceivable Voucher` WHERE `tabReceivable Voucher`.docstatus = 1 AND `tabReceivable Voucher`.%(key)s LIKE "%s" ORDER BY `tabReceivable Voucher`.name desc LIMIT 50';
}
cur_frm.fields_dict.purchase_receipt_no.get_query = function(doc) {
return 'SELECT DISTINCT `tabPurchase Receipt`.name FROM `tabPurchase Receipt` WHERE `tabPurchase Receipt`.docstatus = 1 AND `tabPurchase Receipt`.%(key)s LIKE "%s" ORDER BY `tabPurchase Receipt`.name desc LIMIT 50';
}
// Hide/unhide based on return type
//----------------------------------
cur_frm.cscript.return_type = function(doc, cdt, cdn) {
hide_field(['purchase_receipt_no', 'delivery_note_no', 'sales_invoice_no', 'return_details', 'Get Items', 'Make Excise Invoice', 'Make Stock Entry', 'Make Debit Note', 'Make Credit Note']);
if(doc.return_type == 'Sales Return')
unhide_field(['delivery_note_no', 'sales_invoice_no', 'Get Items', 'return_details', 'Make Credit Note', 'Make Stock Entry', 'Make Excise Invoice']);
else if(doc.return_type == 'Purchase Return')
unhide_field(['purchase_receipt_no', 'Get Items', 'return_details', 'Make Debit Note', 'Make Stock Entry', 'Make Excise Invoice']);
cur_frm.cscript.clear_fields(doc);
}
// Create item table
//-------------------------------
cur_frm.cscript['Get Items'] = function(doc, cdt, cdn) {
flag = 0
if(doc.return_type == 'Sales Return') {
if (doc.delivery_note_no && doc.sales_invoice_no) {
msgprint("You can not enter both Delivery Note No and Sales Invoice No. Please enter any one.");
flag = 1;
} else if (!doc.delivery_note_no && !doc.sales_invoice_no) {
msgprint("Please enter Delivery Note No or Sales Invoice No to proceed");
flag = 1;
}
} else if (doc.return_type == 'Purchase Return' && !doc.purchase_receipt_no) {
msgprint("Please enter Purchase Receipt No to proceed");
flag = 1;
}
if (!flag)
$c_obj(make_doclist(doc.doctype, doc.name),'pull_item_details','', function(r, rt) {
refresh_many(['return_details', 'cust_supp', 'cust_supp_name', 'cust_supp_address']);
});
}
// Clear fields
//-------------------------------
cur_frm.cscript.clear_fields = function(doc) {
doc.purchase_receipt_no, doc.delivery_note_no, doc.sales_invoice_no = '', '', '';
var cl = getchildren('Return Detail', doc.name, 'return_details')
if(cl.length) $c_obj(make_doclist(doc.doctype, doc.name),'clear_return_table','', function(r, rt) {refresh_field('return_details')});
refresh_many(['delivery_note_no', 'sales_invoice_no', 'purchase_receipt_no', 'return_details']);
}
// Make Stock Entry
//-------------------------------
cur_frm.cscript['Make Stock Entry'] = function(doc, cdt, cdn) {
var cl = getchildren('Return Detail', doc.name, 'return_details');
if (!cl.length)
msgprint("Item table can not be blank. Please click on 'Get Items'.");
else if (!cur_frm.cscript.validate_returned_qty(cl)) {
se = cur_frm.cscript.map_parent_fields(doc,cdt,cdn);
cur_frm.cscript.map_child_fields(cl, se);
loaddoc('Stock Entry', se.name);
}
}
// Validate returned qty
//---------------------------
cur_frm.cscript.validate_returned_qty = function(cl) {
flag = 0
for(var i = 0; i<cl.length; i++){
if(cl[i].returned_qty > cl[i].qty) {
msgprint("Returned Qty can not be greater than qty. Please check for item: " + cl[i].item_code);
flag = 1
}
}
return flag
}
// map parent fields of stock entry
//----------------------------------
cur_frm.cscript.map_parent_fields = function(doc, cdt, cdn) {
var se = LocalDB.create('Stock Entry');
se = locals['Stock Entry'][se];
se.posting_date = dateutil.obj_to_str(new Date());
se.transfer_date = dateutil.obj_to_str(new Date());
se.fiscal_year = sys_defaults.fiscal_year;
se.purpose = doc.return_type;
se.remarks = doc.return_type + ' of ' + (doc.delivery_note_no || doc.sales_invoice_no || doc.purchase_receipt_no);
if(doc.return_type == 'Sales Return'){
se.delivery_note_no = doc.delivery_note_no;
se.sales_invoice_no = doc.sales_invoice_no;
se.customer = doc.cust_supp_name;
se.customer_name = doc.cust_supp_name;
se.customer_address = doc.cust_supp_address;
}
else if(doc.return_type == 'Purchase Return'){
se.purchase_receipt_no = doc.purchase_receipt_no;
se.supplier = doc.cust_supp_name;
se.supplier_name = doc.cust_supp_name;
se.supplier_address = doc.cust_supp_address;
}
return se
}
// map child fields of stock entry
//---------------------------------
cur_frm.cscript.map_child_fields = function(cl, se) {
for(var i = 0; i<cl.length; i++){
if (cl[i].returned_qty) {
var d1 = LocalDB.add_child(se, 'Stock Entry Detail', 'mtn_details');
d1.detail_name = cl[i].detail_name;
d1.item_code = cl[i].item_code;
d1.description = cl[i].description;
d1.transfer_qty = cl[i].returned_qty;
d1.qty = cl[i].returned_qty;
d1.stock_uom = cl[i].uom;
d1.uom = cl[i].uom;
d1.conversion_factor = 1;
d1.incoming_rate = cl[i].rate;
d1.serial_no = cl[i].serial_no;
d1.batch_no = cl[i].batch_no;
}
}
}
// Make excise voucher
//-------------------------------
cur_frm.cscript['Make Excise Invoice'] = function(doc) {
var excise = LocalDB.create('Journal Voucher');
excise = locals['Journal Voucher'][excise];
excise.voucher_type = 'Excise Voucher';
loaddoc('Journal Voucher',excise.name);
}
// Make debit note
//------------------------------
cur_frm.cscript['Make Debit Note'] = function(doc) {
cur_frm.cscript.make_jv(doc, 'Debit Note');
}
// Make credit note
//------------------------------
cur_frm.cscript['Make Credit Note'] = function(doc) {
cur_frm.cscript.make_jv(doc, 'Credit Note');
}
// Make JV
//--------------------------------
cur_frm.cscript.make_jv = function(doc, dr_or_cr) {
var jv = LocalDB.create('Journal Voucher');
jv = locals['Journal Voucher'][jv];
jv.voucher_type = dr_or_cr;
jv.company = sys_defaults.company;
jv.fiscal_year = sys_defaults.fiscal_year;
jv.is_opening = 'No';
jv.posting_date = dateutil.obj_to_str(new Date());
jv.voucher_date = dateutil.obj_to_str(new Date());
loaddoc('Journal Voucher',jv.name);
}

View File

@@ -0,0 +1,61 @@
# Please edit this list and import only required elements
import webnotes
from webnotes.utils import add_days, add_months, add_years, cint, cstr, date_diff, default_fields, flt, fmt_money, formatdate, generate_hash, getTraceback, get_defaults, get_first_day, get_last_day, getdate, has_common, month_name, now, nowdate, replace_newlines, sendmail, set_default, str_esc_quote, user_format, validate_email_add
from webnotes.model import db_exists
from webnotes.model.doc import Document, addchild, removechild, getchildren, make_autoname, SuperDocType
from webnotes.model.doclist import getlist, copy_doclist
from webnotes.model.code import get_obj, get_server_obj, run_server_obj, updatedb, check_syntax
from webnotes import session, form, is_testing, msgprint, errprint
set = webnotes.conn.set
sql = webnotes.conn.sql
get_value = webnotes.conn.get_value
in_transaction = webnotes.conn.in_transaction
convert_to_lists = webnotes.conn.convert_to_lists
# -----------------------------------------------------------------------------------------
class DocType :
def __init__(self, doc, doclist=[]):
self.doc = doc
self.doclist = doclist
# Pull Item Details
# ---------------------------
def pull_item_details(self):
if self.doc.return_type == 'Sales Return':
if self.doc.delivery_note_no:
det = sql("select t1.name, t1.item_code, t1.description, t1.qty, t1.uom, t2.basic_rate, t3.customer, t3.customer_name, t3.customer_address, t2.serial_no, t2.batch_no from `tabDelivery Note Packing Detail` t1, `tabDelivery Note Detail` t2, `tabDelivery Note` t3 where t1.parent = t3.name and t2.parent = t3.name and t1.parent_detail_docname = t2.name and t3.name = '%s' and t3.docstatus = 1" % self.doc.delivery_note_no)
elif self.doc.sales_invoice_no:
det = sql("select t1.name, t1.item_code, t1.description, t1.qty, t1.stock_uom, t1.basic_rate, t2.customer, t2.customer_name, t2.customer_address, t1.serial_no from `tabRV Detail` t1, `tabReceivable Voucher` t2 where t1.parent = t2.name and t2.name = '%s' and t2.docstatus = 1" % self.doc.sales_invoice_no)
elif self.doc.return_type == 'Purchase Return' and self.doc.purchase_receipt_no:
det = sql("select t1.name, t1.item_code, t1.description, t1.received_qty, t1.uom, t1.purchase_rate, t2.supplier, t2.supplier_name, t2.supplier_address, t1.serial_no, t1.batch_no from `tabPurchase Receipt Detail` t1, `tabPurchase Receipt` t2 where t1.parent = t2.name and t2.name = '%s' and t2.docstatus = 1" % self.doc.purchase_receipt_no)
self.doc.cust_supp = det and det[0][6] or ''
self.doc.cust_supp_name = det and det[0][7] or ''
self.doc.cust_supp_address = det and det[0][8] or ''
self.create_item_table(det)
self.doc.save()
# Create Item Table
# -----------------------------
def create_item_table(self, det):
self.doc.clear_table(self.doclist, 'return_details', 1)
for i in det:
ch = addchild(self.doc, 'return_details', 'Return Detail', 1, self.doclist)
ch.detail_name = i and i[0] or ''
ch.item_code = i and i[1] or ''
ch.description = i and i[2] or ''
ch.qty = i and flt(i[3]) or 0
ch.uom = i and i[4] or ''
ch.rate = i and flt(i[5]) or 0
ch.serial_no = i and i[9] or ''
ch.batch_no = (len(i) == 11) and i[10] or ''
ch.save()
# Clear return table
# --------------------------------
def clear_return_table(self):
self.doc.clear_table(self.doclist, 'return_details', 1)
self.doc.save()

View File

@@ -0,0 +1,30 @@
$import(Tips Common)
cur_frm.cscript.onload = function(doc, cdt, cdn) {
cur_frm.cscript.get_tips(doc, cdt, cdn);
if(!doc.price_list) set_multiple(cdt,cdn,{price_list:sys_defaults.price_list_name});
}
cur_frm.cscript.refresh = function(doc, cdt, cdn) {
cur_frm.cscript.get_tips(doc, cdt, cdn);
}
/* Get Item Code */
cur_frm.cscript.item_code = function(doc, dt, dn) {
var d = locals[dt][dn];
if (d.item_code){
get_server_fields('get_item_details', d.item_code, 'sales_bom_items', doc ,dt, dn, 1);
}
}
cur_frm.cscript.price_list = function(doc, cdt, cdn) {
$c_obj(make_doclist(cdt,cdn), 'get_rates', '', function(r,rt){refresh_field('sales_bom_items');});
}
cur_frm.cscript.currency = function(doc, cdt, cdn) {
$c_obj(make_doclist(cdt,cdn), 'get_rates', '', function(r,rt){refresh_field('sales_bom_items');});
}
cur_frm.cscript['Find Sales BOM'] = function(doc, dt, dn) {
$c_obj(make_doclist(dt,dn), 'check_duplicate', 1, '');
}

View File

@@ -0,0 +1,205 @@
# Please edit this list and import only required elements
import webnotes
from webnotes.utils import add_days, add_months, add_years, cint, cstr, date_diff, default_fields, flt, fmt_money, formatdate, generate_hash, getTraceback, get_defaults, get_first_day, get_last_day, getdate, has_common, month_name, now, nowdate, replace_newlines, sendmail, set_default, str_esc_quote, user_format, validate_email_add
from webnotes.model import db_exists
from webnotes.model.doc import Document, addchild, removechild, getchildren, make_autoname, SuperDocType
from webnotes.model.doclist import getlist, copy_doclist
from webnotes.model.code import get_obj, get_server_obj, run_server_obj, updatedb, check_syntax
from webnotes import session, form, is_testing, msgprint, errprint
set = webnotes.conn.set
sql = webnotes.conn.sql
get_value = webnotes.conn.get_value
in_transaction = webnotes.conn.in_transaction
convert_to_lists = webnotes.conn.convert_to_lists
# -----------------------------------------------------------------------------------------
class DocType:
def __init__(self,d,dl):
self.doc, self.doclist = d,dl
def autoname(self):
self.doc.name = make_autoname(self.doc.new_item_code)
# Get Ref Rates
# --------------
def get_rates(self):
for d in getlist(self.doclist, "sales_bom_items"):
r = sql("select ref_rate from `tabRef Rate Detail` where price_list_name=%s and parent=%s and ref_currency = %s", (self.doc.price_list, d.item_code, self.doc.currency))
d.rate = r and flt(r[0][0]) or 0.00
# Get Item Details
# -----------------
def get_item_details(self, name):
det = sql("select description, stock_uom from `tabItem` where name = '%s' " % cstr(name))
rate = sql("select ref_rate from `tabRef Rate Detail` where price_list_name = %s and parent = %s and ref_currency = %s", (self.doc.price_list, name, self.doc.currency))
return cstr({'description' : det and det[0][0] or '', 'uom': det and det[0][1] or '', 'rate': rate and flt(rate[0][0]) or 0.00})
def get_main_item(self):
is_main_item = []
for d in getlist(self.doclist,'sales_bom_items'):
if d.is_main_item == 'Yes':
is_main_item.append(d.item_code)
# Check that Sales Bom Item cannot be child of Sales Bom.
if sql("select name from `tabSales BOM` where name = '%s' " % d.item_code):
msgprint("Sales Bom Item " + d.item_code +" cannot be child item.")
raise Exception
# Check if is_main_item is modified once saved
if not self.doc.fields.get('__islocal') and d.is_main_item == "Yes" and cstr(d.item_code) != cstr(self.doc.name)[:-3] :
msgprint("Modifying the main item is not allowed.")
raise Exception
if len(is_main_item) > 1:
msgprint('Main item cannot be more than one.')
raise Exception , " Validation Error."
if len(is_main_item) == 0:
msgprint("At least one item should be main item.")
raise Exception , " Validation Error."
return is_main_item[0]
# Make Item
# ---------
def create_new_item(self):
i = Document("Item")
i.item_code = self.doc.new_item_code
i.item_name = self.doc.new_item_name
i.name = i.item_code
i.is_sales_item = 'Yes'
i.is_stock_item = 'No'
i.save(1)
# This function is deprecated as we will see only pricelist which is selected
# def get_price_lists(self):
# return [i[0] for i in sql("select name from `tabPrice List` where docstatus != 2")]
# Update Rate
# -----------
def update_ref_rate(self, i):
ref_rate,count, p, currency = 0,0, self.doc.price_list, self.doc.currency
if not cstr(self.doc.price_list):
msgprint("Please enter Price List.")
raise Exception
if not cstr(self.doc.currency):
msgprint("Please enter Currency.")
raise Exception
for d in getlist(self.doclist, "sales_bom_items"):
item_rate = sql("select ref_rate,ref_currency from `tabRef Rate Detail` where price_list_name=%s and parent=%s", (p, d.item_code))
if not item_rate:
msgprint("Item %s does not have a rate for Price List %s. Did not update rates for this Price List" % (d.item_code, p))
raise Exception
# if count == 0 : currency = cstr(item_rate[0][1])
if not cstr(currency) == cstr(item_rate[0][1]):
msgprint("Item %s currency %s does not match with other items currency i.e. %s " %(d.item_code,item_rate[0][1],currency))
raise Exception
count += 1
ref_rate += (flt(d.qty) * flt(item_rate[0][0]))
pld = addchild(i,"ref_rate_details", "Ref Rate Detail")
pld.price_list_name = p
pld.ref_rate = flt(ref_rate)
pld.ref_currency = currency
pld.save()
# Update Items
# ------------
def update_item(self):
i = Document("Item", self.doc.new_item_code)
# update fields
i.brand = self.doc.new_item_brand
i.stock_uom = self.doc.stock_uom
i.item_group = self.doc.item_group
# clear old rates
sql("delete from `tabRef Rate Detail` where parent=%s", i.name)
# update rates
new_rates = {}
# pl_list = self.get_price_lists()
#for p in self.get_price_lists():
self.update_ref_rate(i)
# update description and item name
n1, n2 = [], []
for d in getlist(self.doclist, "sales_bom_items"):
n, desc = sql("select item_name, description from tabItem where name=%s", d.item_code)[0]
n1.append(n)
n2.append(desc)
self.doc.new_item_name = (' ').join(n1)
self.doc.description = ("\n" + "\n").join(n2)
i.item_name = self.doc.new_item_name
i.description = self.doc.description
# set default as 'No' or 0 in Item Master as per TIC/3456
i.is_sample_item = 'No'
i.is_asset_item = 'No'
i.is_purchase_item = 'No'
i.is_manufactured_item = 'No'
i.is_sub_contracted_item = 'No'
i.is_service_item = 'No'
i.inspection_required = 'No'
i.has_serial_no = 'No'
i.lead_time_days = flt(0)
i.save()
msgprint("Items updated successfully.")
def validate(self):
# check for duplicate
self.check_duplicate()
item_code = self.get_main_item()
if not self.doc.new_item_code:
self.doc.new_item_code = make_autoname(item_code +'.###')
def on_update(self):
# if no item code, create new item code
if not sql("select name from tabItem where name=%s", self.doc.new_item_code):
self.create_new_item()
self.update_item()
def check_duplicate(self, finder=0):
il = getlist(self.doclist, "sales_bom_items")
if not il:
msgprint("Add atleast one item")
return
# get all Sales BOM that have the first item
sbl = sql("select distinct parent from `tabSales BOM Detail` where item_code=%s", il[0].item_code)
# check all siblings
sub_items = [[d.item_code, flt(d.qty)] for d in il]
for s in sbl:
if not cstr(s[0]) == cstr(self.doc.name) :
t = sql("select item_code, qty from `tabSales BOM Detail` where parent=%s", s[0])
t = [[d[0], flt(d[1])] for d in t]
if self.has_same_items(sub_items, t):
msgprint("%s has the same Sales BOM details" % s[0])
raise Exception
if finder:
msgprint("There is no Sales BOM present with the following Combination.")
def has_same_items(self, l1, l2):
if len(l1)!=len(l2): return 0
for l in l2:
if l not in l1:
return 0
for l in l1:
if l not in l2:
return 0
return 1

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,57 @@
// ************************************** onload ****************************************************
cur_frm.cscript.onload = function(doc, cdt, cdn) {
if(!doc.status) set_multiple(cdt, cdn, {status:'In Store'});
if(doc.__islocal) hide_field(['supplier_name','address_display'])
}
// ************************************** refresh ***************************************************
cur_frm.cscript.refresh = function(doc, cdt, cdn) {
if(!doc.__islocal && doc.warehouse) set_field_permlevel('warehouse', 1);
if(!doc.__islocal && doc.item_code) set_field_permlevel('item_code', 1);
if(doc.__islocal) set_field_permlevel('status', 0);
}
// ************************************** triggers **************************************************
// -------------
// item details
// -------------
cur_frm.add_fetch('item_code', 'item_name', 'item_name')
cur_frm.add_fetch('item_code', 'item_group', 'item_group')
cur_frm.add_fetch('item_code', 'brand', 'brand')
cur_frm.add_fetch('item_code', 'description', 'description')
cur_frm.add_fetch('item_code', 'warranty_period', 'warranty_period')
// ---------
// customer
// ---------
cur_frm.add_fetch('customer', 'customer_name', 'customer_name')
cur_frm.add_fetch('customer', 'address', 'delivery_address')
cur_frm.add_fetch('customer', 'territory', 'territory')
// ---------
// supplier
// ---------
//cur_frm.add_fetch('supplier', 'supplier_name', 'supplier_name')
//cur_frm.add_fetch('customer', 'address', 'supplier_address')
// ----------
// territory
// ----------
cur_frm.fields_dict['territory'].get_query = function(doc,cdt,cdn) {
return 'SELECT `tabTerritory`.`name`,`tabTerritory`.`parent_territory` FROM `tabTerritory` WHERE `tabTerritory`.`is_group` = "No" AND `tabTerritory`.`docstatus`!= 2 AND `tabTerritory`.%(key)s LIKE "%s" ORDER BY `tabTerritory`.`name` ASC LIMIT 50';
}
// Supplier
cur_frm.cscript.supplier = function(doc,dt,dn) {
if(doc.supplier) get_server_fields('get_default_supplier_address', JSON.stringify({supplier: doc.supplier}),'', doc, dt, dn, 1);
if(doc.supplier) unhide_field(['supplier_name','address_display']);
}

View File

@@ -0,0 +1,127 @@
# Please edit this list and import only required elements
import webnotes
from webnotes.utils import cint, flt, cstr, getdate, nowdate
import datetime
sql = webnotes.conn.sql
msgprint = webnotes.msgprint
# -----------------------------------------------------------------------------------------
from utilities.transaction_base import TransactionBase
class DocType(TransactionBase):
def __init__(self, doc, doclist=[]):
self.doc = doc
self.doclist = doclist
# ********************************* validate warranty / amc status ***************************************
# --------------------
# validate amc status
# --------------------
def validate_amc_status(self):
if self.doc.amc_expiry_date and getdate(self.doc.amc_expiry_date) >= datetime.date.today() and self.doc.maintenance_status == 'Out of AMC':
msgprint("AMC expiry date and maintenance status mismatch. Please verify")
raise Exception
elif (not self.doc.amc_expiry_date or getdate(self.doc.amc_expiry_date) < datetime.date.today()) and self.doc.maintenance_status == 'Under AMC':
msgprint("AMC expiry date and maintenance status mismatch. Please verify")
raise Exception
# -------------------------
# validate warranty status
# -------------------------
def validate_warranty_status(self):
if self.doc.warranty_expiry_date and getdate(self.doc.warranty_expiry_date) >= datetime.date.today() and self.doc.maintenance_status == 'Out of Warranty':
msgprint("Warranty expiry date and maintenance status mismatch. Please verify")
raise Exception
elif (not self.doc.warranty_expiry_date or getdate(self.doc.warranty_expiry_date) < datetime.date.today()) and self.doc.maintenance_status == 'Under Warranty':
msgprint("Warranty expiry date and maintenance status mismatch. Please verify")
raise Exception
# -------------------------------
# validate warranty / amc status
# -------------------------------
def validate_warranty_amc_status(self):
self.validate_warranty_status()
self.validate_amc_status()
def validate_warehouse(self):
if self.doc.status=='In Store' and not self.doc.warehouse:
msgprint("Warehouse is mandatory if this Serial No is <b>In Store</b>", raise_exception=1)
def validate_item(self):
item = sql("select name, has_serial_no from tabItem where name = '%s'" % self.doc.item_code)
if not item:
msgprint("Item is not exists in the system", raise_exception=1)
elif item[0][1] == 'No':
msgprint("To proceed please select 'Yes' in 'Has Serial No' in Item master: '%s'" % self.doc.item_code, raise_exception=1)
# ---------
# validate
# ---------
def validate(self):
self.validate_warranty_amc_status()
self.validate_warehouse()
self.validate_item()
# ------------------------
# make stock ledger entry
# ------------------------
def make_stock_ledger_entry(self, update_stock):
from webnotes.model.code import get_obj
values = [{
'item_code' : self.doc.item_code,
'warehouse' : self.doc.warehouse,
'transaction_date' : nowdate(),
'posting_date' : self.doc.purchase_date or (self.doc.creation and self.doc.creation.split(' ')[0]) or nowdate(),
'posting_time' : self.doc.purchase_time or '00:00',
'voucher_type' : 'Serial No',
'voucher_no' : self.doc.name,
'voucher_detail_no' : '',
'actual_qty' : 1,
'stock_uom' : webnotes.conn.get_value('Item', self.doc.item_code, 'stock_uom'),
'incoming_rate' : self.doc.purchase_rate,
'company' : self.doc.company,
'fiscal_year' : self.doc.fiscal_year,
'is_cancelled' : update_stock and 'No' or 'Yes',
'batch_no' : '',
'serial_no' : self.doc.name
}]
get_obj('Stock Ledger', 'Stock Ledger').update_stock(values)
# ----------
# on update
# ----------
def on_update(self):
if self.doc.warehouse and not sql("select name from `tabStock Ledger Entry` where serial_no = '%s'" % (self.doc.name)) and self.doc.status == 'In Store':
self.make_stock_ledger_entry(update_stock = 1)
# ---------
# on trash
# ---------
def on_trash(self):
if self.doc.status == 'Delivered':
msgprint("Cannot trash Serial No : %s as it is already Delivered" % (self.doc.name), raise_exception = 1)
else:
webnotes.conn.set(self.doc, 'status', 'Not in Use')
self.make_stock_ledger_entry(update_stock = 0)
def on_cancel(self):
self.on_trash()
# -----------
# on restore
# -----------
def on_restore(self):
self.make_stock_ledger_entry(update_stock = 1)

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,191 @@
cur_frm.cscript.onload = function(doc, cdt, cdn) {
if (!doc.posting_date) doc.posting_date = dateutil.obj_to_str(new Date());
if (!doc.transfer_date) doc.transfer_date = dateutil.obj_to_str(new Date());
cfn_set_fields(doc, cdt, cdn);
}
var cfn_set_fields = function(doc, cdt, cdn) {
lst = ['supplier','supplier_name','supplier_address','customer','customer_name','customer_address'];
if (doc.purpose == 'Production Order'){
unhide_field(['production_order', 'process', 'Get Items']);
hide_field(['from_warehouse', 'to_warehouse','purchase_receipt_no','delivery_note_no', 'sales_invoice_no','Warehouse HTML']);
doc.from_warehouse = '';
doc.to_warehosue = '';
if (doc.process == 'Backflush'){
unhide_field('fg_completed_qty');
}
else{
hide_field('fg_completed_qty');
doc.fg_completed_qty = 0;
}
}
else{
unhide_field(['from_warehouse', 'to_warehouse']);
hide_field(['production_order', 'process', 'Get Items', 'fg_completed_qty','purchase_receipt_no','delivery_note_no', 'sales_invoice_no']);
hide_field(lst);
doc.production_order = '';
doc.process = '';
doc.fg_completed_qty = 0;
}
if(doc.purpose == 'Purchase Return'){
doc.customer=doc.customer_name = doc.customer_address=doc.delivery_note_no=doc.sales_invoice_no='';
hide_field(lst);
unhide_field(['supplier','supplier_name','supplier_address','purchase_receipt_no']);
}
if(doc.purpose == 'Sales Return'){
doc.supplier=doc.supplier_name = doc.supplier_address=doc.purchase_receipt_no='';
hide_field(lst);
unhide_field(['customer','customer_name','customer_address','delivery_note_no', 'sales_invoice_no']);
} else{
doc.customer=doc.customer_name=doc.customer_address=doc.delivery_note_no=doc.sales_invoice_no=doc.supplier=doc.supplier_name = doc.supplier_address=doc.purchase_receipt_no='';
}
refresh_many(lst);
}
cur_frm.cscript.delivery_note_no = function(doc,cdt,cdn){
if(doc.delivery_note_no) get_server_fields('get_cust_values','','',doc,cdt,cdn,1);
}
cur_frm.cscript.sales_invoice_no = function(doc,cdt,cdn){
if(doc.sales_invoice_no) get_server_fields('get_cust_values','','',doc,cdt,cdn,1);
}
cur_frm.cscript.customer = function(doc,cdt,cdn){
if(doc.customer) get_server_fields('get_cust_addr','','',doc,cdt,cdn,1);
}
cur_frm.cscript.purchase_receipt_no = function(doc,cdt,cdn){
if(doc.purchase_receipt_no) get_server_fields('get_supp_values','','',doc,cdt,cdn,1);
}
cur_frm.cscript.supplier = function(doc,cdt,cdn){
if(doc.supplier) get_server_fields('get_supp_addr','','',doc,cdt,cdn,1);
}
cur_frm.fields_dict['production_order'].get_query = function(doc) {
return 'SELECT DISTINCT `tabProduction Order`.`name` FROM `tabProduction Order` WHERE `tabProduction Order`.`docstatus` = 1 AND `tabProduction Order`.`qty` > ifnull(`tabProduction Order`.`produced_qty`,0) AND `tabProduction Order`.`name` like "%s" ORDER BY `tabProduction Order`.`name` DESC LIMIT 50';
}
cur_frm.cscript.purpose = function(doc, cdt, cdn) {
cfn_set_fields(doc, cdt, cdn);
}
cur_frm.cscript.process = function(doc, cdt, cdn) {
cfn_set_fields(doc, cdt, cdn);
}
//
// item code - only if quantity present in source warehosue
//
var fld = cur_frm.fields_dict['mtn_details'].grid.get_field('item_code');
fld.query_description = "If Source Warehouse is selected, only items present in the warehouse with actual qty > 0 will be selected"
fld.get_query = function(doc, cdt, cdn) {
var d = locals[cdt][cdn];
if(d.s_warehouse) {
return 'SELECT tabItem.name, tabItem.description, tabBin.actual_qty '
+'FROM tabItem, tabBin '
+'WHERE tabItem.name = tabBin.item_code '
+'AND ifnull(`tabBin`.`actual_qty`,0) > 0 '
+'AND tabBin.warehouse="'+ d.s_warehouse +'" '
+'AND tabItem.docstatus < 2 '
+'AND tabItem.%(key)s LIKE "%s" '
+'ORDER BY tabItem.name ASC '
+'LIMIT 50'
} else {
return 'SELECT tabItem.name, tabItem.description '
+'FROM tabItem '
+'WHERE tabItem.docstatus < 2 '
+'AND tabItem.%(key)s LIKE "%s" '
+'ORDER BY tabItem.name ASC '
+'LIMIT 50'
}
}
//
// copy over source and target warehouses
//
cur_frm.fields_dict['mtn_details'].grid.onrowadd = function(doc, cdt, cdn){
var d = locals[cdt][cdn];
if(!d.s_warehouse && doc.from_warehouse) {
d.s_warehouse = doc.from_warehouse
refresh_field('s_warehouse', cdn, 'mtn_details')
}
if(!d.t_warehouse && doc.to_warehouse) {
d.t_warehouse = doc.to_warehouse
refresh_field('t_warehouse', cdn, 'mtn_details')
}
}
//========================= Overloaded query for link batch_no =============================================================
cur_frm.fields_dict['mtn_details'].grid.get_field('batch_no').get_query= function(doc, cdt, cdn) {
var d = locals[cdt][cdn];
if(d.item_code){
return "SELECT tabBatch.name, tabBatch.description FROM tabBatch WHERE tabBatch.docstatus != 2 AND tabBatch.item = '"+ d.item_code +"' AND `tabBatch`.`name` like '%s' ORDER BY `tabBatch`.`name` DESC LIMIT 50"
}
else{
alert("Please enter Item Code.");
}
}
//==================================================================================================================
cur_frm.cscript.item_code = function(doc, cdt, cdn) {
var d = locals[cdt][cdn];
cal_back = function(r, rt){ /*cur_frm.cscript.calc_amount(doc)*/}
// get values
args = {
item_code: d.item_code,
warehouse: cstr(d.s_warehouse)
};
get_server_fields('get_item_details',JSON.stringify(args),'mtn_details',doc,cdt,cdn,1,cal_back);
}
//==================================================================================================================
cur_frm.cscript.transfer_qty = function(doc,cdt,cdn) {
var d = locals[cdt][cdn];
if (doc.from_warehouse && (flt(d.transfer_qty) > flt(d.actual_qty))) {
alert("Transfer Quantity is more than Available Qty");
}
}
//==================================================================================================================
cur_frm.cscript.qty = function(doc, cdt, cdn) {
var d = locals[cdt][cdn];
set_multiple('Stock Entry Detail', d.name, {'transfer_qty': flt(d.qty) * flt(d.conversion_factor)}, 'mtn_details');
refresh_field('mtn_details');
}
//==================================================================================================================
cur_frm.cscript.uom = function(doc, cdt, cdn) {
var d = locals[cdt][cdn];
if(d.uom && d.item_code){
var arg = {'item_code':d.item_code, 'uom':d.uom, 'qty':d.qty}
get_server_fields('get_uom_details',JSON.stringify(arg),'mtn_details', doc, cdt, cdn, 1);
}
}
//==================================================================================================================
//validate
cur_frm.cscript.validate = function(doc, cdt, cdn) {
cur_frm.cscript.validate_items(doc);
}
//==================================================================================================================
//validate items
cur_frm.cscript.validate_items = function(doc) {
cl = getchildren('Stock Entry Detail',doc.name,'mtn_details');
if (!cl.length) {
alert("Item table can not be blank");
validated = false;
}
}

View File

@@ -0,0 +1,416 @@
# Please edit this list and import only required elements
import webnotes
from webnotes.utils import add_days, add_months, add_years, cint, cstr, date_diff, default_fields, flt, fmt_money, formatdate, generate_hash, getTraceback, get_defaults, get_first_day, get_last_day, getdate, has_common, month_name, now, nowdate, replace_newlines, sendmail, set_default, str_esc_quote, user_format, validate_email_add
from webnotes.model import db_exists, delete_doc
from webnotes.model.doc import Document, addchild, removechild, getchildren, make_autoname, SuperDocType
from webnotes.model.doclist import getlist, copy_doclist
from webnotes.model.code import get_obj, get_server_obj, run_server_obj, updatedb, check_syntax
from webnotes import session, form, is_testing, msgprint, errprint
set = webnotes.conn.set
sql = webnotes.conn.sql
get_value = webnotes.conn.get_value
in_transaction = webnotes.conn.in_transaction
convert_to_lists = webnotes.conn.convert_to_lists
# -----------------------------------------------------------------------------------------
class DocType:
def __init__(self, doc, doclist=[]):
self.doc = doc
self.doclist = doclist
self.item_dict = {}
self.fname = 'mtn_details'
# Autoname
# ---------
def autoname(self):
self.doc.name = make_autoname(self.doc.naming_series+'.#####')
# get item details
# ----------------
def get_item_details(self, arg):
arg, bin, in_rate = eval(arg), None, 0
item = sql("select stock_uom, description, item_name from `tabItem` where name = %s and (ifnull(end_of_life,'')='' or end_of_life ='0000-00-00' or end_of_life > now())", (arg['item_code']), as_dict = 1)
if not item:
if arg['item_code']:
msgprint("Item is not active. You can restore it from Trash")
raise webnotes.ValidationError
if arg['warehouse']:
bin = sql("select actual_qty from `tabBin` where item_code = %s and warehouse = %s", (arg['item_code'], arg['warehouse']), as_dict = 1)
in_rate = get_obj('Valuation Control').get_incoming_rate(self.doc.posting_date, self.doc.posting_time, arg['item_code'],arg['warehouse'])
ret = {
'uom' : item and item[0]['stock_uom'] or '',
'stock_uom' : item and item[0]['stock_uom'] or '',
'description' : item and item[0]['description'] or '',
'item_name' : item and item[0]['item_name'] or '',
'actual_qty' : bin and flt(bin[0]['actual_qty']) or 0,
'qty' : 0,
'transfer_qty' : 0,
'incoming_rate' : flt(in_rate),
'conversion_factor' : 1,
'batch_no' : ''
}
return str(ret)
# Get UOM Details
def get_uom_details(self, arg = ''):
arg, ret = eval(arg), {}
uom = sql("select conversion_factor from `tabUOM Conversion Detail` where parent = %s and uom = %s", (arg['item_code'],arg['uom']), as_dict = 1)
if not uom:
msgprint("There is no Conversion Factor for UOM '%s' in Item '%s'" % (arg['uom'], arg['item_code']))
ret = {'uom' : ''}
else:
ret = {
'conversion_factor' : flt(uom[0]['conversion_factor']),
'transfer_qty' : flt(arg['qty']) * flt(uom[0]['conversion_factor']),
}
return str(ret)
# get rate of FG item
#---------------------------
def get_in_rate(self, pro_obj):
# calculate_cost for production item
get_obj('BOM Control').calculate_cost(pro_obj.doc.bom_no)
# return cost
return flt(get_obj('Bill Of Materials', pro_obj.doc.bom_no).doc.cost_as_per_mar)
# get current_stock
# ----------------
def get_current_stock(self, pro_obj = ''):
for d in getlist(self.doclist, 'mtn_details'):
d.s_warehouse = (self.doc.purpose != 'Production Order') and self.doc.from_warehouse or cstr(d.s_warehouse)
d.t_warehouse = (self.doc.purpose != 'Production Order') and self.doc.to_warehouse or cstr(d.t_warehouse)
if d.s_warehouse:
bin = sql("select actual_qty from `tabBin` where item_code = %s and warehouse = %s", (d.item_code, d.s_warehouse), as_dict = 1)
d.actual_qty = bin and flt(bin[0]['actual_qty']) or 0
else:
d.actual_qty = 0
if d.fg_item:
d.incoming_rate = pro_obj and self.get_in_rate(pro_obj) or ''
elif self.doc.purpose not in ['Material Receipt', 'Sales Return'] and not d.incoming_rate and d.s_warehouse:
d.incoming_rate = flt(get_obj('Valuation Control').get_incoming_rate(self.doc.posting_date, self.doc.posting_time, d.item_code, d.s_warehouse, d.transfer_qty, d.serial_no))
d.save()
# makes dict of unique items with it's qty
#-----------------------------------------
def make_items_dict(self, items_list):
# items_list = [[item_name, qty]]
for i in items_list:
if self.item_dict.has_key(i[0]):
self.item_dict[i[0]][0] = flt(self.item_dict[i[0]][0]) + flt(i[1])
else:
self.item_dict[i[0]] = [flt(i[1]), cstr(i[2]), cstr(i[3])]
def get_raw_materials(self,pro_obj):
# get all items from flat bom except, child items of sub-contracted and sub assembly items and sub assembly items itself.
flat_bom_items = sql("select item_code, ifnull(sum(qty_consumed_per_unit), 0) * '%s', description, stock_uom from `tabFlat BOM Detail` where parent = '%s' and parent_bom = '%s' and is_pro_applicable = 'No' and docstatus < 2 group by item_code" % ((self.doc.process == 'Backflush') and flt(self.doc.fg_completed_qty) or flt(pro_obj.doc.qty), cstr(pro_obj.doc.bom_no), cstr(pro_obj.doc.bom_no)))
self.make_items_dict(flat_bom_items)
if pro_obj.doc.consider_sa_items == 'Yes':
# get all Sub Assembly items only from flat bom
fl_bom_sa_items = sql("select item_code, ifnull(sum(qty_consumed_per_unit), 0) * '%s', description, stock_uom from `tabFlat BOM Detail` where parent = '%s' and parent_bom != '%s' and is_pro_applicable = 'Yes' and docstatus < 2 group by item_code" % ((self.doc.process == 'Backflush') and flt(self.doc.fg_completed_qty) or flt(pro_obj.doc.qty), cstr(pro_obj.doc.bom_no), cstr(pro_obj.doc.bom_no)))
self.make_items_dict(fl_bom_sa_items)
if pro_obj.doc.consider_sa_items == 'No':
# get all sub assembly childs only from flat bom
fl_bom_sa_child_item = sql("select item_code, ifnull(sum(qty_consumed_per_unit), 0) * '%s', description, stock_uom from `tabFlat BOM Detail` where parent = '%s' and parent_bom in (select distinct parent_bom from `tabFlat BOM Detail` where parent = '%s' and parent_bom != '%s' and is_pro_applicable = 'Yes' and docstatus < 2 ) and is_pro_applicable = 'No' and docstatus < 2 group by item_code" % ((self.doc.process == 'Backflush') and flt(self.doc.fg_completed_qty) or flt(pro_obj.doc.qty), cstr(pro_obj.doc.bom_no), cstr(pro_obj.doc.bom_no), cstr(pro_obj.doc.bom_no)))
self.make_items_dict(fl_bom_sa_child_item)
def add_to_stock_entry_detail(self, pro_obj, item_dict, fg_item = 0):
sw, tw = '', ''
if self.doc.process == 'Material Transfer':
tw = cstr(pro_obj.doc.wip_warehouse)
if self.doc.process == 'Backflush':
tw = fg_item and cstr(pro_obj.doc.fg_warehouse) or ''
if not fg_item: sw = cstr(pro_obj.doc.wip_warehouse)
for d in item_dict:
se_child = addchild(self.doc, 'mtn_details', 'Stock Entry Detail', 0, self.doclist)
se_child.s_warehouse = sw
se_child.t_warehouse = tw
se_child.fg_item = fg_item
se_child.item_code = cstr(d)
se_child.description = item_dict[d][1]
se_child.uom = item_dict[d][2]
se_child.stock_uom = item_dict[d][2]
se_child.reqd_qty = flt(item_dict[d][0])
se_child.qty = flt(item_dict[d][0])
se_child.transfer_qty = flt(item_dict[d][0])
se_child.conversion_factor = 1.00
# get items
#------------------
def get_items(self):
pro_obj = self.doc.production_order and get_obj('Production Order', self.doc.production_order) or ''
self.validate_for_production_order(pro_obj)
self.get_raw_materials(pro_obj)
self.doc.clear_table(self.doclist, 'mtn_details', 1)
self.add_to_stock_entry_detail(pro_obj, self.item_dict)
if self.doc.process == 'Backflush':
item_dict = {cstr(pro_obj.doc.production_item) : [self.doc.fg_completed_qty, pro_obj.doc.description, pro_obj.doc.stock_uom]}
self.add_to_stock_entry_detail(pro_obj, item_dict, fg_item = 1)
def validate_transfer_qty(self):
for d in getlist(self.doclist, 'mtn_details'):
if flt(d.transfer_qty) <= 0:
msgprint("Transfer Quantity can not be less than or equal to zero at Row No " + cstr(d.idx))
raise Exception
if d.s_warehouse:
if flt(d.transfer_qty) > flt(d.actual_qty):
msgprint("Transfer Quantity is more than Available Qty at Row No " + cstr(d.idx))
raise Exception
def calc_amount(self):
total_amount = 0
for d in getlist(self.doclist, 'mtn_details'):
d.amount = flt(d.transfer_qty) * flt(d.incoming_rate)
total_amount += flt(d.amount)
self.doc.total_amount = flt(total_amount)
def add_to_values(self, d, wh, qty, is_cancelled):
self.values.append({
'item_code' : d.item_code,
'warehouse' : wh,
'transaction_date' : self.doc.transfer_date,
'posting_date' : self.doc.posting_date,
'posting_time' : self.doc.posting_time,
'voucher_type' : 'Stock Entry',
'voucher_no' : self.doc.name,
'voucher_detail_no' : d.name,
'actual_qty' : qty,
'incoming_rate' : flt(d.incoming_rate) or 0,
'stock_uom' : d.stock_uom,
'company' : self.doc.company,
'fiscal_year' : self.doc.fiscal_year,
'is_cancelled' : (is_cancelled ==1) and 'Yes' or 'No',
'batch_no' : d.batch_no,
'serial_no' : d.serial_no
})
def update_stock_ledger(self, is_cancelled=0):
self.values = []
for d in getlist(self.doclist, 'mtn_details'):
if cstr(d.s_warehouse):
self.add_to_values(d, cstr(d.s_warehouse), -flt(d.transfer_qty), is_cancelled)
if cstr(d.t_warehouse):
self.add_to_values(d, cstr(d.t_warehouse), flt(d.transfer_qty), is_cancelled)
get_obj('Stock Ledger', 'Stock Ledger').update_stock(self.values)
def validate_for_production_order(self, pro_obj):
if self.doc.purpose == 'Production Order' or self.doc.process or self.doc.production_order or flt(self.doc.fg_completed_qty):
if self.doc.purpose != 'Production Order':
msgprint("Purpose should be 'Production Order'.")
raise Exception
if not self.doc.process:
msgprint("Process Field is mandatory.")
raise Exception
if self.doc.process == 'Backflush' and not flt(self.doc.fg_completed_qty):
msgprint("FG Completed Qty is mandatory as the process selected is 'Backflush'")
raise Exception
if self.doc.process == 'Material Transfer' and flt(self.doc.fg_completed_qty):
msgprint("FG Completed Qty should be zero. As the Process selected is 'Material Transfer'.")
raise Exception
if not self.doc.production_order:
msgprint("Production Order field is mandatory")
raise Exception
if flt(pro_obj.doc.qty) < flt(pro_obj.doc.produced_qty) + flt(self.doc.fg_completed_qty) :
msgprint("error:Already Produced Qty for %s is %s and maximum allowed Qty is %s" % (pro_obj.doc.production_item, cstr(pro_obj.doc.produced_qty) or 0.00 , cstr(pro_obj.doc.qty)))
raise Exception
# Validate
# ------------------
def validate(self):
sl_obj = get_obj("Stock Ledger", "Stock Ledger")
sl_obj.scrub_serial_nos(self)
sl_obj.validate_serial_no(self, 'mtn_details')
pro_obj = ''
if self.doc.production_order:
pro_obj = get_obj('Production Order', self.doc.production_order)
self.validate_for_production_order(pro_obj)
self.validate_incoming_rate()
self.validate_warehouse(pro_obj)
self.get_current_stock(pro_obj)
self.calc_amount()
get_obj('Sales Common').validate_fiscal_year(self.doc.fiscal_year,self.doc.posting_date,'Posting Date')
# If target warehouse exists, incoming rate is mandatory
# --------------------------------------------------------
def validate_incoming_rate(self):
for d in getlist(self.doclist, 'mtn_details'):
if not flt(d.incoming_rate) and d.t_warehouse:
msgprint("Rate is mandatory for Item: %s at row %s" % (d.item_code, d.idx), raise_exception=1)
# Validate warehouse
# -----------------------------------
def validate_warehouse(self, pro_obj):
fg_qty = 0
for d in getlist(self.doclist, 'mtn_details'):
if not d.s_warehouse and not d.t_warehouse:
d.s_warehouse = self.doc.from_warehouse
d.t_warehouse = self.doc.to_warehouse
if not (d.s_warehouse or d.t_warehouse):
msgprint("Atleast one warehouse is mandatory for Stock Entry ")
raise Exception
if d.s_warehouse and not sql("select name from tabWarehouse where name = '%s'" % d.s_warehouse):
msgprint("Invalid Warehouse: %s" % self.doc.s_warehouse)
raise Exception
if d.t_warehouse and not sql("select name from tabWarehouse where name = '%s'" % d.t_warehouse):
msgprint("Invalid Warehouse: %s" % self.doc.t_warehouse)
raise Exception
if d.s_warehouse == d.t_warehouse:
msgprint("Source and Target Warehouse Cannot be Same.")
raise Exception
if self.doc.purpose == 'Material Issue':
if not cstr(d.s_warehouse):
msgprint("Source Warehouse is Mandatory for Purpose => 'Material Issue'")
raise Exception
if cstr(d.t_warehouse):
msgprint("Target Warehouse is not Required for Purpose => 'Material Issue'")
raise Exception
if self.doc.purpose == 'Material Transfer':
if not cstr(d.s_warehouse) or not cstr(d.t_warehouse):
msgprint("Source Warehouse and Target Warehouse both are Mandatory for Purpose => 'Material Transfer'")
raise Exception
if self.doc.purpose == 'Material Receipt':
if not cstr(d.t_warehouse):
msgprint("Target Warehouse is Mandatory for Purpose => 'Material Receipt'")
raise Exception
if cstr(d.s_warehouse):
msgprint("Source Warehouse is not Required for Purpose => 'Material Receipt'")
raise Exception
if self.doc.process == 'Material Transfer':
if cstr(d.t_warehouse) != (pro_obj.doc.wip_warehouse):
msgprint(" Target Warehouse should be same as WIP Warehouse %s in Production Order %s at Row No %s" % (cstr(pro_obj.doc.wip_warehouse), cstr(pro_obj.doc.name), cstr(d.idx)) )
raise Exception
if not cstr(d.s_warehouse):
msgprint("Please Enter Source Warehouse at Row No %s is mandatory." % (cstr(d.idx)))
raise Exception
if self.doc.process == 'Backflush':
if flt(d.fg_item):
if cstr(pro_obj.doc.production_item) != cstr(d.item_code):
msgprint("Item %s in Stock Entry Detail as Row No %s do not match with Item %s in Production Order %s" % (cstr(d.item_code), cstr(d.idx), cstr(pro_obj.doc.production_item), cstr(pro_obj.doc.name)))
raise Exception
fg_qty = flt(fg_qty) + flt(d.transfer_qty)
if cstr(d.t_warehouse) != cstr(pro_obj.doc.fg_warehouse):
msgprint("As Item %s is FG Item. Target Warehouse should be same as FG Warehouse %s in Production Order %s, at Row No %s. " % ( cstr(d.item_code), cstr(pro_obj.doc.fg_warehouse), cstr(pro_obj.doc.name), cstr(d.idx)))
raise Exception
if cstr(d.s_warehouse):
msgprint("As Item %s is a FG Item. There should be no Source Warehouse at Row No %s" % (cstr(d.item_code), cstr(d.idx)))
raise Exception
if not flt(d.fg_item):
if cstr(d.t_warehouse):
msgprint("As Item %s is not a FG Item. There should no Tareget Warehouse at Row No %s" % (cstr(d.item_code), cstr(d.idx)))
raise Exception
if cstr(d.s_warehouse) != cstr(pro_obj.doc.wip_warehouse):
msgprint("As Item %s is Raw Material. Source Warehouse should be same as WIP Warehouse %s in Production Order %s, at Row No %s. " % ( cstr(d.item_code), cstr(pro_obj.doc.wip_warehouse), cstr(pro_obj.doc.name), cstr(d.idx)))
raise Exception
d.save()
if self.doc.fg_completed_qty and flt(self.doc.fg_completed_qty) != flt(fg_qty):
msgprint("The Total of FG Qty %s in Stock Entry Detail do not match with FG Completed Qty %s" % (flt(fg_qty), flt(self.doc.fg_completed_qty)))
raise Exception
def update_production_order(self, is_submit):
if self.doc.production_order:
pro_obj = get_obj("Production Order", self.doc.production_order)
if flt(pro_obj.doc.docstatus) != 1:
msgprint("One cannot do any transaction against Production Order : %s, as it's not submitted" % (pro_obj.doc.name))
raise Exception
if pro_obj.doc.status == 'Stopped':
msgprint("One cannot do any transaction against Production Order : %s, as it's status is 'Stopped'" % (pro_obj.doc.name))
raise Exception
if getdate(pro_obj.doc.posting_date) > getdate(self.doc.posting_date):
msgprint("Posting Date of Stock Entry cannot be before Posting Date of Production Order "+ cstr(self.doc.production_order))
raise Exception
if self.doc.process == 'Backflush':
pro_obj.doc.produced_qty = flt(pro_obj.doc.produced_qty) + (is_submit and 1 or -1 ) * flt(self.doc.fg_completed_qty)
get_obj('Warehouse', pro_obj.doc.fg_warehouse).update_bin(0, 0, 0, 0, (is_submit and 1 or -1 ) * flt(self.doc.fg_completed_qty), pro_obj.doc.production_item, now())
pro_obj.doc.status = (flt(pro_obj.doc.qty) == flt(pro_obj.doc.produced_qty)) and 'Completed' or 'In Process'
pro_obj.doc.save()
# Create / Update Serial No
# ----------------------------------
def update_serial_no(self, is_submit):
sl_obj = get_obj('Stock Ledger')
for d in getlist(self.doclist, 'mtn_details'):
if d.serial_no:
serial_nos = sl_obj.get_sr_no_list(d.serial_no)
for x in serial_nos:
serial_no = x.strip()
if d.s_warehouse:
sl_obj.update_serial_delivery_details(self, d, serial_no, is_submit)
if d.t_warehouse:
sl_obj.update_serial_purchase_details(self, d, serial_no, is_submit, (self.doc.purpose in ['Material Transfer', 'Sales Return']) and 1 or 0)
if self.doc.purpose == 'Purchase Return':
delete_doc("Serial No", serial_no)
# On Submit
# ------------------
def on_submit(self):
self.validate_transfer_qty()
# Check for Approving Authority
get_obj('Authorization Control').validate_approving_authority(self.doc.doctype, self.doc.company, self.doc.total_amount)
self.update_serial_no(1)
self.update_stock_ledger(0)
# update Production Order
self.update_production_order(1)
# On Cancel
# -------------------
def on_cancel(self):
self.update_serial_no(0)
self.update_stock_ledger(1)
# update Production Order
self.update_production_order(0)
def get_cust_values(self):
tbl = self.doc.delivery_note_no and 'Delivery Note' or 'Receivable Voucher'
record_name = self.doc.delivery_note_no or self.doc.sales_invoice_no
res = sql("select customer,customer_name, customer_address from `tab%s` where name = '%s'" % (tbl, record_name))
ret = {
'customer' : res and res[0][0] or '',
'customer_name' : res and res[0][1] or '',
'customer_address' : res and res[0][2] or ''}
return str(ret)
def get_cust_addr(self):
res = sql("select customer_name,address from `tabCustomer` where name = '%s'"%self.doc.customer)
ret = {
'customer_name' : res and res[0][0] or '',
'customer_address' : res and res[0][1] or ''}
return str(ret)
def get_supp_values(self):
res = sql("select supplier,supplier_name,supplier_address from `tabPurchase Receipt` where name = '%s'"%self.doc.purchase_receipt_no)
ret = {
'supplier' : res and res[0][0] or '',
'supplier_name' :res and res[0][1] or '',
'supplier_address' : res and res[0][2] or ''}
return str(ret)
def get_supp_addr(self):
res = sql("select supplier_name,address from `tabSupplier` where name = '%s'"%self.doc.supplier)
ret = {
'supplier_name' : res and res[0][0] or '',
'supplier_address' : res and res[0][1] or ''}
return str(ret)

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,651 @@
[
{
'_last_update': None,
'allow_attach': None,
'allow_copy': None,
'allow_email': None,
'allow_print': None,
'allow_rename': None,
'allow_trash': None,
'autoname': 'MTND/.######',
'change_log': None,
'client_script': None,
'client_script_core': None,
'client_string': None,
'colour': 'White:FFF',
'creation': '2010-08-08 17:09:25',
'description': None,
'docstatus': 0,
'doctype': 'DocType',
'document_type': None,
'dt_template': None,
'hide_heading': None,
'hide_toolbar': None,
'idx': None,
'in_create': None,
'in_dialog': None,
'is_transaction_doc': None,
'issingle': None,
'istable': 1,
'max_attachments': None,
'menu_index': None,
'modified': '2011-04-26 11:47:18',
'modified_by': 'Administrator',
'module': 'Material Management',
'name': 'Stock Entry Detail',
'name_case': None,
'owner': 'Administrator',
'parent': None,
'parent_node': None,
'parentfield': None,
'parenttype': None,
'print_outline': None,
'read_only': None,
'read_only_onload': None,
'search_fields': None,
'section_style': 'Tray',
'server_code': None,
'server_code_compiled': None,
'server_code_core': None,
'server_code_error': ' ',
'show_in_menu': 0,
'smallicon': None,
'use_template': None,
'version': 24
},
{
'allow_on_submit': None,
'colour': None,
'creation': '2010-08-08 17:09:25',
'default': None,
'depends_on': None,
'description': None,
'docstatus': 0,
'doctype': 'DocField',
'fieldname': 's_warehouse',
'fieldtype': 'Link',
'hidden': None,
'icon': None,
'idx': 1,
'in_filter': 1,
'label': 'Source Warehouse',
'modified': '2011-04-26 11:47:18',
'modified_by': 'Administrator',
'name': 'FL03404',
'no_copy': None,
'oldfieldname': 's_warehouse',
'oldfieldtype': 'Link',
'options': 'Warehouse',
'owner': 'jai@webnotestech.com',
'parent': 'Stock Entry Detail',
'parentfield': 'fields',
'parenttype': 'DocType',
'permlevel': 2,
'print_hide': None,
'report_hide': None,
'reqd': None,
'search_index': None,
'trigger': None,
'width': None
},
{
'allow_on_submit': None,
'colour': None,
'creation': '2010-08-08 17:09:25',
'default': None,
'depends_on': None,
'description': None,
'docstatus': 0,
'doctype': 'DocField',
'fieldname': 't_warehouse',
'fieldtype': 'Link',
'hidden': None,
'icon': None,
'idx': 2,
'in_filter': 1,
'label': 'Target Warehouse',
'modified': '2011-04-26 11:47:18',
'modified_by': 'Administrator',
'name': 'FL03405',
'no_copy': None,
'oldfieldname': 't_warehouse',
'oldfieldtype': 'Link',
'options': 'Warehouse',
'owner': 'jai@webnotestech.com',
'parent': 'Stock Entry Detail',
'parentfield': 'fields',
'parenttype': 'DocType',
'permlevel': 2,
'print_hide': None,
'report_hide': None,
'reqd': None,
'search_index': None,
'trigger': None,
'width': None
},
{
'allow_on_submit': None,
'colour': None,
'creation': '2010-08-08 17:09:25',
'default': None,
'depends_on': None,
'description': None,
'docstatus': 0,
'doctype': 'DocField',
'fieldname': 'fg_item',
'fieldtype': 'Check',
'hidden': None,
'icon': None,
'idx': 3,
'in_filter': 1,
'label': 'FG Item',
'modified': '2011-04-26 11:47:18',
'modified_by': 'Administrator',
'name': 'FL03406',
'no_copy': None,
'oldfieldname': 'fg_item',
'oldfieldtype': 'Check',
'options': None,
'owner': 'jai@webnotestech.com',
'parent': 'Stock Entry Detail',
'parentfield': 'fields',
'parenttype': 'DocType',
'permlevel': 2,
'print_hide': 1,
'report_hide': None,
'reqd': None,
'search_index': None,
'trigger': None,
'width': None
},
{
'allow_on_submit': None,
'colour': None,
'creation': '2010-08-08 17:09:25',
'default': None,
'depends_on': None,
'description': None,
'docstatus': 0,
'doctype': 'DocField',
'fieldname': 'item_code',
'fieldtype': 'Link',
'hidden': None,
'icon': None,
'idx': 4,
'in_filter': 1,
'label': 'Item Code',
'modified': '2011-04-26 11:47:18',
'modified_by': 'Administrator',
'name': 'FL03407',
'no_copy': None,
'oldfieldname': 'item_code',
'oldfieldtype': 'Link',
'options': 'Item',
'owner': 'Administrator',
'parent': 'Stock Entry Detail',
'parentfield': 'fields',
'parenttype': 'DocType',
'permlevel': 0,
'print_hide': None,
'report_hide': None,
'reqd': 1,
'search_index': 1,
'trigger': 'Client',
'width': None
},
{
'allow_on_submit': None,
'colour': None,
'creation': '2011-04-26 11:47:18',
'default': None,
'depends_on': None,
'description': None,
'docstatus': 0,
'doctype': 'DocField',
'fieldname': 'item_name',
'fieldtype': 'Data',
'hidden': None,
'icon': None,
'idx': 5,
'in_filter': 1,
'label': 'Item Name',
'modified': '2011-04-26 11:47:18',
'modified_by': 'Administrator',
'name': '000002665',
'no_copy': None,
'oldfieldname': None,
'oldfieldtype': None,
'options': None,
'owner': 'Administrator',
'parent': 'Stock Entry Detail',
'parentfield': 'fields',
'parenttype': 'DocType',
'permlevel': 0,
'print_hide': None,
'report_hide': None,
'reqd': None,
'search_index': 1,
'trigger': None,
'width': None
},
{
'allow_on_submit': None,
'colour': None,
'creation': '2010-08-08 17:09:25',
'default': None,
'depends_on': None,
'description': None,
'docstatus': 0,
'doctype': 'DocField',
'fieldname': 'description',
'fieldtype': 'Text',
'hidden': None,
'icon': None,
'idx': 6,
'in_filter': None,
'label': 'Description',
'modified': '2011-04-26 11:47:18',
'modified_by': 'Administrator',
'name': 'FL03408',
'no_copy': None,
'oldfieldname': 'description',
'oldfieldtype': 'Text',
'options': None,
'owner': 'Administrator',
'parent': 'Stock Entry Detail',
'parentfield': 'fields',
'parenttype': 'DocType',
'permlevel': 0,
'print_hide': None,
'report_hide': None,
'reqd': None,
'search_index': None,
'trigger': None,
'width': '300px'
},
{
'allow_on_submit': None,
'colour': None,
'creation': '2010-08-08 17:09:25',
'default': None,
'depends_on': None,
'description': None,
'docstatus': 0,
'doctype': 'DocField',
'fieldname': 'batch_no',
'fieldtype': 'Link',
'hidden': None,
'icon': None,
'idx': 7,
'in_filter': None,
'label': 'Batch No',
'modified': '2011-04-26 11:47:18',
'modified_by': 'Administrator',
'name': 'FL03409',
'no_copy': None,
'oldfieldname': 'batch_no',
'oldfieldtype': 'Link',
'options': 'Batch',
'owner': 'harshada@webnotestech.com',
'parent': 'Stock Entry Detail',
'parentfield': 'fields',
'parenttype': 'DocType',
'permlevel': 0,
'print_hide': 1,
'report_hide': None,
'reqd': None,
'search_index': None,
'trigger': 'Client',
'width': None
},
{
'allow_on_submit': None,
'colour': None,
'creation': '2010-08-08 17:09:25',
'default': None,
'depends_on': None,
'description': None,
'docstatus': 0,
'doctype': 'DocField',
'fieldname': 'actual_qty',
'fieldtype': 'Read Only',
'hidden': None,
'icon': None,
'idx': 8,
'in_filter': 1,
'label': 'Actual Qty (at source)',
'modified': '2011-04-26 11:47:18',
'modified_by': 'Administrator',
'name': 'FL03410',
'no_copy': 1,
'oldfieldname': 'actual_qty',
'oldfieldtype': 'Read Only',
'options': None,
'owner': 'Administrator',
'parent': 'Stock Entry Detail',
'parentfield': 'fields',
'parenttype': 'DocType',
'permlevel': 1,
'print_hide': 1,
'report_hide': None,
'reqd': 0,
'search_index': 1,
'trigger': None,
'width': None
},
{
'allow_on_submit': None,
'colour': None,
'creation': '2010-12-14 10:23:23',
'default': None,
'depends_on': None,
'description': None,
'docstatus': 0,
'doctype': 'DocField',
'fieldname': 'qty',
'fieldtype': 'Currency',
'hidden': None,
'icon': None,
'idx': 9,
'in_filter': None,
'label': 'Qty',
'modified': '2011-04-26 11:47:18',
'modified_by': 'Administrator',
'name': 'FL04245',
'no_copy': None,
'oldfieldname': 'qty',
'oldfieldtype': 'Currency',
'options': None,
'owner': 'ashwini@webnotestech.com',
'parent': 'Stock Entry Detail',
'parentfield': 'fields',
'parenttype': 'DocType',
'permlevel': 0,
'print_hide': None,
'report_hide': None,
'reqd': 1,
'search_index': None,
'trigger': 'Client',
'width': None
},
{
'allow_on_submit': None,
'colour': None,
'creation': '2010-08-08 17:09:25',
'default': None,
'depends_on': None,
'description': None,
'docstatus': 0,
'doctype': 'DocField',
'fieldname': 'reqd_qty',
'fieldtype': 'Currency',
'hidden': None,
'icon': None,
'idx': 10,
'in_filter': 0,
'label': 'Reqd Qty',
'modified': '2011-04-26 11:47:18',
'modified_by': 'Administrator',
'name': 'FL03412',
'no_copy': None,
'oldfieldname': 'reqd_qty',
'oldfieldtype': 'Currency',
'options': None,
'owner': 'jai@webnotestech.com',
'parent': 'Stock Entry Detail',
'parentfield': 'fields',
'parenttype': 'DocType',
'permlevel': 3,
'print_hide': 1,
'report_hide': None,
'reqd': None,
'search_index': None,
'trigger': None,
'width': None
},
{
'allow_on_submit': None,
'colour': 'White:FFF',
'creation': '2010-12-14 16:34:12',
'default': None,
'depends_on': None,
'description': None,
'docstatus': 0,
'doctype': 'DocField',
'fieldname': 'uom',
'fieldtype': 'Link',
'hidden': None,
'icon': None,
'idx': 11,
'in_filter': None,
'label': 'UOM',
'modified': '2011-04-26 11:47:18',
'modified_by': 'Administrator',
'name': 'FL04299',
'no_copy': None,
'oldfieldname': 'uom',
'oldfieldtype': 'Link',
'options': 'UOM',
'owner': 'Administrator',
'parent': 'Stock Entry Detail',
'parentfield': 'fields',
'parenttype': 'DocType',
'permlevel': 0,
'print_hide': None,
'report_hide': None,
'reqd': 1,
'search_index': None,
'trigger': 'Client',
'width': None
},
{
'allow_on_submit': None,
'colour': None,
'creation': '2010-12-14 10:23:23',
'default': None,
'depends_on': None,
'description': None,
'docstatus': 0,
'doctype': 'DocField',
'fieldname': 'conversion_factor',
'fieldtype': 'Currency',
'hidden': None,
'icon': None,
'idx': 12,
'in_filter': None,
'label': 'Conversion Factor',
'modified': '2011-04-26 11:47:18',
'modified_by': 'Administrator',
'name': 'FL04246',
'no_copy': None,
'oldfieldname': 'conversion_factor',
'oldfieldtype': 'Currency',
'options': None,
'owner': 'ashwini@webnotestech.com',
'parent': 'Stock Entry Detail',
'parentfield': 'fields',
'parenttype': 'DocType',
'permlevel': 1,
'print_hide': None,
'report_hide': None,
'reqd': 1,
'search_index': None,
'trigger': None,
'width': None
},
{
'allow_on_submit': None,
'colour': None,
'creation': '2010-08-08 17:09:25',
'default': None,
'depends_on': None,
'description': None,
'docstatus': 0,
'doctype': 'DocField',
'fieldname': 'stock_uom',
'fieldtype': 'Link',
'hidden': None,
'icon': None,
'idx': 13,
'in_filter': 0,
'label': 'Stock UOM',
'modified': '2011-04-26 11:47:18',
'modified_by': 'Administrator',
'name': 'FL03411',
'no_copy': None,
'oldfieldname': 'stock_uom',
'oldfieldtype': 'Link',
'options': 'UOM',
'owner': 'Administrator',
'parent': 'Stock Entry Detail',
'parentfield': 'fields',
'parenttype': 'DocType',
'permlevel': 1,
'print_hide': None,
'report_hide': None,
'reqd': 1,
'search_index': 0,
'trigger': None,
'width': None
},
{
'allow_on_submit': None,
'colour': None,
'creation': '2010-08-08 17:09:25',
'default': None,
'depends_on': None,
'description': None,
'docstatus': 0,
'doctype': 'DocField',
'fieldname': 'transfer_qty',
'fieldtype': 'Currency',
'hidden': None,
'icon': None,
'idx': 14,
'in_filter': None,
'label': 'Stock Qty',
'modified': '2011-04-26 11:47:18',
'modified_by': 'Administrator',
'name': 'FL03413',
'no_copy': None,
'oldfieldname': 'transfer_qty',
'oldfieldtype': 'Currency',
'options': None,
'owner': 'Administrator',
'parent': 'Stock Entry Detail',
'parentfield': 'fields',
'parenttype': 'DocType',
'permlevel': 1,
'print_hide': None,
'report_hide': None,
'reqd': 1,
'search_index': None,
'trigger': None,
'width': None
},
{
'allow_on_submit': None,
'colour': None,
'creation': '2010-08-08 17:09:25',
'default': None,
'depends_on': None,
'description': None,
'docstatus': 0,
'doctype': 'DocField',
'fieldname': 'serial_no',
'fieldtype': 'Text',
'hidden': None,
'icon': None,
'idx': 15,
'in_filter': None,
'label': 'Serial No',
'modified': '2011-04-26 11:47:18',
'modified_by': 'Administrator',
'name': 'FL03414',
'no_copy': None,
'oldfieldname': 'serial_no',
'oldfieldtype': 'Text',
'options': None,
'owner': 'Administrator',
'parent': 'Stock Entry Detail',
'parentfield': 'fields',
'parenttype': 'DocType',
'permlevel': 0,
'print_hide': None,
'report_hide': None,
'reqd': None,
'search_index': None,
'trigger': None,
'width': None
},
{
'allow_on_submit': None,
'colour': None,
'creation': '2010-08-08 17:09:25',
'default': None,
'depends_on': None,
'description': None,
'docstatus': 0,
'doctype': 'DocField',
'fieldname': 'incoming_rate',
'fieldtype': 'Currency',
'hidden': None,
'icon': None,
'idx': 16,
'in_filter': None,
'label': 'Incoming Rate',
'modified': '2011-04-26 11:47:18',
'modified_by': 'Administrator',
'name': 'FL03415',
'no_copy': None,
'oldfieldname': 'incoming_rate',
'oldfieldtype': 'Currency',
'options': None,
'owner': 'Administrator',
'parent': 'Stock Entry Detail',
'parentfield': 'fields',
'parenttype': 'DocType',
'permlevel': 0,
'print_hide': None,
'report_hide': None,
'reqd': 0,
'search_index': None,
'trigger': None,
'width': None
},
{
'allow_on_submit': None,
'colour': None,
'creation': '2010-08-08 17:09:25',
'default': None,
'depends_on': None,
'description': None,
'docstatus': 0,
'doctype': 'DocField',
'fieldname': 'amount',
'fieldtype': 'Currency',
'hidden': None,
'icon': None,
'idx': 17,
'in_filter': None,
'label': 'Amount',
'modified': '2011-04-26 11:47:18',
'modified_by': 'Administrator',
'name': 'FL03416',
'no_copy': None,
'oldfieldname': 'amount',
'oldfieldtype': 'Currency',
'options': None,
'owner': 'Administrator',
'parent': 'Stock Entry Detail',
'parentfield': 'fields',
'parenttype': 'DocType',
'permlevel': 1,
'print_hide': None,
'report_hide': None,
'reqd': None,
'search_index': None,
'trigger': None,
'width': None
}
]

View File

@@ -0,0 +1,237 @@
# Please edit this list and import only required elements
import webnotes
from webnotes.utils import add_days, add_months, add_years, cint, cstr, date_diff, default_fields, flt, fmt_money, formatdate, generate_hash, getTraceback, get_defaults, get_first_day, get_last_day, getdate, has_common, month_name, now, nowdate, replace_newlines, sendmail, set_default, str_esc_quote, user_format, validate_email_add
from webnotes.model import db_exists
from webnotes.model.doc import Document, addchild, removechild, getchildren, make_autoname, SuperDocType
from webnotes.model.doclist import getlist, copy_doclist
from webnotes.model.code import get_obj, get_server_obj, run_server_obj, updatedb, check_syntax
from webnotes import session, form, is_testing, msgprint, errprint
set = webnotes.conn.set
sql = webnotes.conn.sql
get_value = webnotes.conn.get_value
in_transaction = webnotes.conn.in_transaction
convert_to_lists = webnotes.conn.convert_to_lists
# -----------------------------------------------------------------------------------------
def get_sr_no_list(sr_nos, qty = 0):
serial_nos = cstr(sr_nos).strip().replace(',', '\n').split('\n')
valid_serial_nos = []
for val in serial_nos:
if val:
if val in valid_serial_nos:
msgprint("You have entered duplicate serial no: %s" % val, raise_exception=1)
else:
valid_serial_nos.append(val.strip())
if qty > 0 and cstr(sr_nos).strip() and len(valid_serial_nos) != flt(qty):
msgprint("Please enter serial nos for all "+ cstr(qty) + " quantity", raise_exception = 1)
return valid_serial_nos
class DocType:
def __init__(self, doc, doclist=[]):
self.doc = doc
self.doclist = doclist
# -----------------
# scrub serial nos
# -----------------
def scrub_serial_nos(self, obj):
for d in getlist(obj.doclist, obj.fname):
if d.serial_no:
d.serial_no = d.serial_no.replace(',', '\n')
d.save()
# -----------------------------
# validate serial no warehouse
# -----------------------------
def validate_serial_no_warehouse(self, obj, fname):
for d in getlist(obj.doclist, fname):
if d.serial_no:
serial_nos = self.get_sr_no_list(d.serial_no)
for s in serial_nos:
s = s.strip()
sr_war = sql("select warehouse from `tabSerial No` where name = '%s'" % (s))
if not sr_war:
msgprint("Please set a warehouse in the Serial No <b>%s</b>" % s, raise_exception = 1)
if sr_war[0][0] != d.warehouse:
msgprint("Serial No : %s for Item : %s doesn't exists in Warehouse : %s" % (s, d.item_code, d.warehouse), raise_exception = 1)
# ------------------------------------
# check whether serial no is required
# ------------------------------------
def validate_serial_no(self, obj, fname):
for d in getlist(obj.doclist, fname):
is_stock_item = get_value('Item', d.item_code, 'is_stock_item')
ar_required = get_value('Item', d.item_code, 'has_serial_no')
if cstr(d.serial_no).strip():
if is_stock_item != 'Yes':
msgprint("Serial No is not required for non-stock item: %s" % d.item_code, raise_exception=1)
elif ar_required != 'Yes':
msgprint("If serial no required, please select 'Yes' in 'Has Serial No' in Item :" + d.item_code + ', otherwise please remove serial no', raise_exception=1)
elif ar_required == 'Yes' and not d.serial_no:
msgprint("Serial no is mandatory for item: "+ d.item_code, raise_exception = 1)
# -------------------
# get serial no list
# -------------------
def get_sr_no_list(self, sr_nos, qty = 0):
return get_sr_no_list(sr_nos, qty)
# ---------------------
# set serial no values
# ---------------------
def set_pur_serial_no_values(self, obj, serial_no, d, s, new_rec):
item_details = sql("select item_group, warranty_period from `tabItem` where name = '%s' and (ifnull(end_of_life,'')='' or end_of_life = '0000-00-00' or end_of_life > now()) " %(d.item_code), as_dict=1)
s.purchase_document_type = obj.doc.doctype
s.purchase_document_no = obj.doc.name
s.purchase_date = obj.doc.posting_date
s.purchase_time = obj.doc.posting_time
s.purchase_rate = d.purchase_rate or d.incoming_rate
s.item_code = d.item_code
s.brand = d.brand
s.description = d.description
s.item_group = item_details and item_details[0]['item_group'] or ''
s.warranty_period = item_details and item_details[0]['warranty_period'] or 0
s.supplier = obj.doc.supplier
s.supplier_name = obj.doc.supplier_name
s.supplier_address = obj.doc.supplier_address
s.warehouse = d.warehouse or d.t_warehouse
s.docstatus = 0
s.status = 'In Store'
s.modified = nowdate()
s.modified_by = session['user']
s.serial_no = serial_no
s.fiscal_year = obj.doc.fiscal_year
s.company = obj.doc.company
s.save(new_rec)
# ----------------------------------
# update serial no purchase details
# ----------------------------------
def update_serial_purchase_details(self, obj, d, serial_no, is_submit, is_transfer = 0):
exists = sql("select name, status, docstatus from `tabSerial No` where name = '%s'" % (serial_no))
if is_submit:
if exists and exists[0][2] != 2 and not is_transfer:
msgprint("Serial No: %s already %s" % (serial_no, exists and exists[0][1]), raise_exception = 1)
elif exists:
s = Document('Serial No', exists and exists[0][0])
self.set_pur_serial_no_values(obj, serial_no, d, s, new_rec = 0)
else:
s = Document('Serial No')
self.set_pur_serial_no_values(obj, serial_no, d, s, new_rec = 1)
else:
if exists and exists[0][1] == 'Delivered' and exists[0][2] != 2:
msgprint("Serial No: %s is already delivered, you can not cancel the document." % serial_no, raise_exception=1)
else:
sql("update `tabSerial No` set docstatus = '%s', status = '%s', purchase_document_type = '', purchase_document_no = '', purchase_date = '', purchase_rate = '', supplier = null, supplier_name = '', supplier_address = '', warehouse = null where name = '%s'" % (not is_transfer and 2 or 0, is_transfer and 'In Store' or 'Not in Use', serial_no))
# -------------------------------
# check whether serial no exists
# -------------------------------
def check_serial_no_exists(self, serial_no, item_code):
chk = sql("select name, status, docstatus, item_code from `tabSerial No` where name = %s", (serial_no), as_dict=1)
if not chk:
msgprint("Serial No: %s does not exists in the system" % serial_no, raise_exception=1)
elif chk and chk[0]['item_code'] != item_code:
msgprint("Serial No: %s not belong to item: %s" % (serial_no, item_code), raise_exception=1)
elif chk and chk[0]['docstatus'] == 2:
msgprint("Serial No: %s of Item : %s is trashed in the system" % (serial_no, item_code), raise_exception = 1)
elif chk and chk[0]['status'] == 'Delivered':
msgprint("Serial No: %s of Item : %s is already delivered." % (serial_no, item_code), raise_exception = 1)
# ---------------------
# set serial no values
# ---------------------
def set_delivery_serial_no_values(self, obj, serial_no):
s = Document('Serial No', serial_no)
s.delivery_document_type = obj.doc.doctype
s.delivery_document_no = obj.doc.name
s.delivery_date = obj.doc.posting_date
s.delivery_time = obj.doc.posting_time
s.customer = obj.doc.customer
s.customer_name = obj.doc.customer_name
s.delivery_address = obj.doc.delivery_address
s.territory = obj.doc.territory
s.warranty_expiry_date = s.warranty_period and add_days(cstr(obj.doc.posting_date), s.warranty_period) or ''
s.docstatus = 1
s.status = 'Delivered'
s.modified = nowdate()
s.modified_by = session['user']
s.save()
# ----------------------------------
# update serial no delivery details
# ----------------------------------
def update_serial_delivery_details(self, obj, d, serial_no, is_submit):
if is_submit:
self.check_serial_no_exists(serial_no, d.item_code)
self.set_delivery_serial_no_values(obj, serial_no)
else:
sql("update `tabSerial No` set docstatus = 0, status = 'In Store', delivery_document_type = '', delivery_document_no = '', delivery_date = '', customer = null, customer_name = '', delivery_address = '', territory = null where name = '%s'" % (serial_no))
# ---------------------
# update serial record
# ---------------------
def update_serial_record(self, obj, fname, is_submit = 1, is_incoming = 0):
import datetime
for d in getlist(obj.doclist, fname):
if d.serial_no:
serial_nos = self.get_sr_no_list(d.serial_no, d.qty)
for a in serial_nos:
serial_no = a.strip()
if is_incoming:
self.update_serial_purchase_details(obj, d, serial_no, is_submit)
else:
self.update_serial_delivery_details(obj, d, serial_no, is_submit)
# -------------
# update stock
# -------------
def update_stock(self, values):
for v in values:
sle_id, serial_nos = '', ''
# get serial nos
if v["serial_no"]:
serial_nos = self.get_sr_no_list(v["serial_no"], v['actual_qty'])
# reverse quantities for cancel
if v['is_cancelled'] == 'Yes':
v['actual_qty'] = -flt(v['actual_qty'])
# cancel matching entry
sql("update `tabStock Ledger Entry` set is_cancelled='Yes' where voucher_no=%s and voucher_type=%s", (v['voucher_no'], v['voucher_type']))
if v["actual_qty"]:
sle_id = self.make_entry(v)
get_obj('Warehouse', v["warehouse"]).update_bin(flt(v["actual_qty"]), 0, 0, 0, 0, v["item_code"], v["posting_date"], sle_id, v["posting_time"], '')
# -----------
# make entry
# -----------
def make_entry(self, args):
sle = Document(doctype = 'Stock Ledger Entry')
for k in args.keys():
# adds warehouse_type
if k == 'warehouse':
sle.fields['warehouse_type'] = get_value('Warehouse' , args[k], 'warehouse_type')
sle.fields[k] = args[k]
sle_obj = get_obj(doc=sle)
# validate
sle_obj.validate()
sle.save(new = 1)
return sle.name

View File

@@ -0,0 +1 @@
[{'section_style': 'Simple', 'is_transaction_doc': None, 'creation': '2009-03-12 12:09:43', 'search_fields': None, 'module': 'Material Management', 'doctype': 'DocType', 'change_log': None, 'print_outline': '', 'owner': 'Administrator', 'in_dialog': None, 'in_create': 1, 'read_only': 1, 'allow_email': None, 'dt_template': None, 'hide_heading': None, 'issingle': 1, 'allow_rename': None, 'smallicon': '', 'allow_attach': None, 'show_in_menu': 0, 'max_attachments': None, 'version': 10, 'menu_index': None, 'docstatus': 0, 'allow_copy': None, 'istable': None, 'description': None, 'parent': None, 'server_code': '', 'allow_trash': None, 'allow_print': None, 'autoname': None, 'client_script_core': None, 'client_string': None, 'use_template': None, 'modified_by': 'nabin@webnotestech.com', 'document_type': None, 'name': 'Stock Ledger', 'idx': None, 'hide_toolbar': 1, 'colour': 'White:FFF', 'client_script': '', 'modified': '2010-09-20 14:06:57', 'server_code_error': ' ', 'name_case': '', 'parenttype': None, 'read_only_onload': None, 'server_code_core': None, 'server_code_compiled': None, 'parent_node': None, 'parentfield': None}, {'cancel': None, 'amend': None, 'execute': None, 'modified_by': 'nabin@webnotestech.com', 'name': 'PERM00198', 'parent': 'Stock Ledger', 'read': 1, 'create': None, 'creation': '2009-03-12 14:53:41', 'modified': '2010-08-07 01:10:02', 'submit': None, 'doctype': 'DocPerm', 'write': None, 'idx': 1, 'parenttype': 'DocType', 'role': 'All', 'owner': 'Administrator', 'docstatus': 0, 'permlevel': 1, 'match': None, 'parentfield': 'permissions'}, {'cancel': None, 'amend': None, 'execute': None, 'modified_by': 'nabin@webnotestech.com', 'name': 'PERM00206', 'parent': 'Stock Ledger', 'read': 1, 'create': None, 'creation': '2009-03-12 15:09:54', 'modified': '2010-08-07 01:10:02', 'submit': None, 'doctype': 'DocPerm', 'write': None, 'idx': 2, 'parenttype': 'DocType', 'role': 'Material User', 'owner': 'Administrator', 'docstatus': 0, 'permlevel': 1, 'match': None, 'parentfield': 'permissions'}]

View File

@@ -0,0 +1,81 @@
# Please edit this list and import only required elements
import webnotes
from webnotes.utils import cstr, cint, flt, cstr, getdate
sql = webnotes.conn.sql
get_value = webnotes.conn.get_value
msgprint = webnotes.msgprint
# -----------------------------------------------------------------------------------------
class DocType:
def __init__(self, doc, doclist=[]):
self.doc = doc
self.doclist = doclist
#check for item quantity available in stock
def actual_amt_check(self):
if self.doc.batch_no:
batch_bal = flt(sql("select sum(actual_qty) from `tabStock Ledger Entry` where warehouse = '%s' and item_code = '%s' and batch_no = '%s'"%(self.doc.warehouse,self.doc.item_code,self.doc.batch_no))[0][0])
if (batch_bal + self.doc.actual_qty) < 0:
msgprint("""Not enough quantity (requested: %(actual_qty)s, current: %(batch_bal)s in Batch
<b>%(batch_no)s</b> for Item <b>%(item_code)s</b> at Warehouse<b>%(warehouse)s</b>
as on %(posting_date)s %(posting_time)s""" % self.doc.fields.update({'batch_bal': batch_bal}), raise_exception = 1)
# mandatory
# ---------
def validate_mandatory(self):
mandatory = ['warehouse','transaction_date','posting_date','voucher_type','voucher_no','actual_qty','company','fiscal_year']
for k in mandatory:
if self.doc.fields.get(k)==None:
msgprint("Stock Ledger Entry: '%s' is mandatory" % k, raise_exception = 1)
elif k == 'warehouse':
if not sql("select name from tabWarehouse where name = '%s'" % self.doc.fields.get(k)):
msgprint("Warehouse: '%s' does not exist in the system. Please check." % self.doc.fields.get(k), raise_exception = 1)
# validate for item
# -----------------
def validate_item(self):
item_det = sql("select name, has_batch_no, docstatus from tabItem where name = '%s'" % self.doc.item_code)
# check item exists
if item_det:
item_det = item_det and item_det[0]
else:
msgprint("Item: '%s' does not exist in the system. Please check." % self.doc.item_code, raise_exception = 1)
# check if item is trashed
if cint(item_det[2])==2:
msgprint("Item: '%s' is trashed, cannot make a stock transaction against a trashed item" % self.doc.item_code, raise_exception = 1)
# check if batch number is required
if item_det[1]=='Yes' and self.doc.voucher_type != 'Stock Reconciliation':
if not self.doc.batch_no:
msgprint("Batch number is mandatory for Item '%s'" % self.doc.item_code, raise_exception = 1)
raise Exception
# check if batch belongs to item
if not sql("select name from `tabBatch` where item='%s' and name ='%s' and docstatus != 2" % (self.doc.item_code, self.doc.batch_no)):
msgprint("'%s' is not a valid Batch Number for Item '%s'" % (self.doc.batch_no, self.doc.item_code), raise_exception = 1)
# Nobody can do SL Entries where posting date is before freezing date except authorized person
#----------------------------------------------------------------------------------------------
def check_stock_frozen_date(self):
stock_frozen_upto = get_value('Manage Account', None, 'stock_frozen_upto') or ''
if stock_frozen_upto:
stock_auth_role = get_value('Manage Account', None,'stock_auth_role')
if getdate(self.doc.posting_date) <= getdate(stock_frozen_upto) and not stock_auth_role in webnotes.user.get_roles():
msgprint("You are not authorized to do / modify back dated stock entries before %s" % getdate(stock_frozen_upto).strftime('%d-%m-%Y'), raise_exception=1)
def validate(self):
self.validate_mandatory()
self.validate_item()
self.actual_amt_check()
self.check_stock_frozen_date()

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,37 @@
cur_frm.cscript.onload = function(doc, cdt, cdn) {
cfn_set_fields(doc, cdt, cdn);
}
cur_frm.cscript.refresh = function(doc, cdt, cdn) {
cfn_set_fields(doc, cdt, cdn);
}
var cfn_set_fields = function(doc, cdt, cdn) {
refresh_field('remark');
refresh_field('next_step');
if (doc.docstatus == 0 && doc.next_step == 'Upload File and Save Document')
doc.next_step = 'Validate Data';
if (! doc.file_list)
doc.next_step = 'Upload File and Save Document'
if (doc.next_step == 'Upload File and Save Document') {
//alert("Upload File and Save Document");
cur_frm.clear_tip();
cur_frm.set_tip("Please Enter Reconciliation Date and Attach CSV File with Columns in Following Sequence:-");
cur_frm.append_tip("Item Code , Warehouse , Qty , MAR");
hide_field("Validate Data");
}
if (doc.next_step == 'Validate Data') {
//alert("Validate Data");
cur_frm.clear_tip();
cur_frm.set_tip("Please Check Remarks");
unhide_field("Validate Data");
}
if (doc.next_step == 'Submit Document') {
//alert('Submit Document');
cur_frm.clear_tip();
cur_frm.set_tip("Please Submit the document.");
hide_field("Validate Data");
}
}

View File

@@ -0,0 +1,309 @@
# Please edit this list and import only required elements
import webnotes
from webnotes.utils import add_days, add_months, add_years, cint, cstr, date_diff, default_fields, flt, fmt_money, formatdate, generate_hash, getTraceback, get_defaults, get_first_day, get_last_day, getdate, has_common, month_name, now, nowdate, replace_newlines, sendmail, set_default, str_esc_quote, user_format, validate_email_add
from webnotes.model import db_exists
from webnotes.model.doc import Document, addchild, removechild, getchildren, make_autoname, SuperDocType
from webnotes.model.doclist import getlist, copy_doclist
from webnotes.model.code import get_obj, get_server_obj, run_server_obj, updatedb, check_syntax
from webnotes import session, form, is_testing, msgprint, errprint
set = webnotes.conn.set
sql = webnotes.conn.sql
get_value = webnotes.conn.get_value
in_transaction = webnotes.conn.in_transaction
convert_to_lists = webnotes.conn.convert_to_lists
# -----------------------------------------------------------------------------------------
class DocType:
def __init__(self, doc, doclist=[]):
self.doc = doc
self.doclist = doclist
self.label = { 'item_code': 0 , 'warehouse': 1 , 'qty': 2, 'mar': 3,'stock_uom':4, 'actual_qty':5, 'diff': 6} # with mar
# autoname
#-----------------
def autoname(self):
self.doc.name = make_autoname('SR/' + self.doc.fiscal_year + '/.######')
# -----------------
# update next step
# -----------------
def update_next_step(self,next_step):
sql("update `tabStock Reconciliation` set next_step = '%s' where name = '%s'" % (next_step,self.doc.name))
# -----------
# add remark
# -----------
def add_remark(self, text, next_step, first_time = 0):
if first_time:
sql("update `tabStock Reconciliation` set remark = '' where name = '%s'" % self.doc.name)
else:
sql("update `tabStock Reconciliation` set remark = concat(remark, '%s'), modified = '%s' where name = '%s'" % (text + "<br>", nowdate(), self.doc.name))
self.update_next_step(next_step)
# --------------
# validate item
# --------------
def validate_item(self, item, count, check_item = 1):
det = sql("select item_code, has_serial_no from `tabItem` where name = '%s'"% cstr(item), as_dict = 1)
if not det:
text = "Item: " + cstr(item) + " mentioned at Row No. " + cstr(count) + "does not exist in the system"
msgprint(text)
self.add_remark(text, 'Validate Data', 0)
check_item = 0
elif det and det[0]['has_serial_no'] == 'Yes':
text = "You cannot make Stock Reconciliation of items having serial no. You can directly upload serial no to update their inventory. Please remove Item Code : %s at Row No. %s" %(cstr(item), cstr(count))
msgprint(text)
self.add_remark(text, 'Validate Data', 0)
check_item = 0
return check_item
# -------------------
# validate warehouse
# -------------------
def validate_warehouse(self,wh,count, check_warehouse = 1):
if not sql("select name from `tabWarehouse` where name = '%s'" % cstr(wh)):
text = "Warehouse: " + cstr(wh) + " mentioned at Row No. " + cstr(count) + "does not exist in the system"
self.add_remark(text,'Validate Data',0)
check_warehouse = 0
return check_warehouse
# ---------------------------
# validate data of .csv file
# ---------------------------
def validate_data(self,stock):
self.add_remark('','Validate Data',1)
# check whether file uploaded
if not self.doc.file_list:
set(self.doc,'next_step','Upload File and Save Document')
msgprint("Please Attach File", raise_exception=1)
# validate item and warehouse
check_item,check_warehouse,count = 1, 1, 1
for s in stock:
count +=1
check_item = self.validate_item(s[self.label['item_code']],count) or 0
check_warehouse = self.validate_warehouse(s[self.label['warehouse']],count) or 0
if check_item and check_warehouse:
text = "Validation Completed Successfully..."
self.add_remark(text,'Submit Document',0)
return check_item and check_warehouse
# ------------------------------
# convert lines in .csv to list
# ------------------------------
def convert_into_list(self, stock, submit):
count, st_list = 1, []
for s in stock:
if submit and len(s) != 4:
msgprint("Data entered at Row No " + cstr(count) + " in Attachment File is not in correct format.", raise_exception=1)
l = [s[0].encode("ascii"), s[1].encode("ascii"), s[2].encode("ascii"), s[3].encode("ascii")]
st_list.append(l)
count += 1
return st_list
# ------------------
# get current stock
# ------------------
def get_current_stock(self, item_code, warehouse):
bin = sql("select name from `tabBin` where item_code = '%s' and warehouse = '%s'" % (item_code, warehouse))
prev_sle = bin and get_obj('Bin', bin[0][0]).get_prev_sle('', self.doc.reconciliation_date,self.doc.reconciliation_time) or 0
stock_uom = sql("select stock_uom from `tabItem` where name = %s",item_code)
return {'actual_qty': prev_sle.get('bin_aqat', 0), 'stock_uom': stock_uom[0][0]}
# -----------
# update mar
# -----------
def update_mar(self, d, qty_diff):
if not d[self.label['qty']] and not d[self.label['actual_qty']]:
# seems like a special condition when there is no actual quanitity but there is a rate, may be only for setting a rate!
self.make_sl_entry(1,d,1)
self.make_sl_entry(-1,d,1)
else:
self.update_item_valuation_pre_date(d)
if not qty_diff:
self.update_item_valuation_post_date()
# update valuation rate as csv file in all sle before reconciliation date
# ------------------------------------------------------------------------
def update_item_valuation_pre_date(self, d):
mar = flt(d[self.label['mar']])
# previous sle
prev_sle = sql("""
select name, fcfs_stack
from `tabStock Ledger Entry`
where item_code = '%s'
and warehouse = '%s'
and timestamp(posting_date, posting_time) <= timestamp(%s, %s)
""", (d[self.label['item_code']], d[self.label['warehouse']], self.doc.reconciliation_date, self.doc.reconciliation_time))
for each in prev_sle:
# updated fifo stack
fstack = [[i[0], mar] for i in each]
# update incoming rate, valuation rate, stock value and fifo stack
sql(""" update `tabStock Ledger Entry`
set incoming_rate = %s, valuation_rate = %s, stock_value = bin_aqat*%s, fcfs_stack = %s
where name = '%s'
""", (mar, mar, mar, fstack, each[0]))
# Update item valuation in all sle after the reconcliation date
# ---------------------------------------------------------
def update_item_valuation_post_date(self, d):
bin = sql("select name from `tabBin` where item_code = '%s' and warehouse = '%s'" % (d[self.label['item_code']], d[self.label['warehouse']]))
bin_obj = get_obj('Bin', bin[0][0])
# prev sle
prev_sle = bin_obj.get_prev_sle('', self.doc.reconciliation_date,self.doc.reconciliation_time)
# update valuation in sle posted after reconciliation datetime
bin_obj.update_item_valuation(posting_date = self.doc.reconciliation_date, posting_time = self.doc.reconciliation_time, prev_sle = prev_sle)
# --------------
# make sl entry
# --------------
def make_sl_entry(self, update_stock, stock, diff):
values = []
values.append({
'item_code' : stock[self.label['item_code']],
'warehouse' : stock[self.label['warehouse']],
'transaction_date' : now(),
'posting_date' : self.doc.reconciliation_date,
'posting_time' : self.doc.reconciliation_time,
'voucher_type' : self.doc.doctype,
'voucher_no' : self.doc.name,
'voucher_detail_no' : self.doc.name,
'actual_qty' : flt(update_stock) * flt(diff),
'stock_uom' : stock[self.label['stock_uom']],
'incoming_rate' : stock[self.label['mar']] or 0,
'company' : self.doc.company,
'fiscal_year' : self.doc.fiscal_year,
'is_cancelled' : (update_stock==1) and 'No' or 'Yes',
'batch_no' : '',
'serial_no' : ''
})
get_obj('Stock Ledger', 'Stock Ledger').update_stock(values)
# -----------------------
# get stock reco details
# -----------------------
def get_reconciliation_stock_details(self,submit = 0):
import csv
stock = csv.reader(self.get_csv_file_data().splitlines())
stock = self.convert_into_list(stock, submit)
if stock[0][0] and stock[0][0].strip()=='Item Code':
stock.pop(0) # remove the labels
check = self.validate_data(stock)
if not check:
return 0
return stock
# validate date and time
# ------------------------
def validate_datetime(self):
if not self.doc.reconciliation_date:
msgprint("Please Enter Reconciliation Date.", raise_exception=1)
if not self.doc.reconciliation_time:
msgprint("Please Enter Reconciliation Time.", raise_exception=1)
# ----------------------
# stock reconciliations
# ----------------------
def stock_reconciliations(self, submit = 0):
self.validate_datetime()
# get reco data
rec_stock_detail = self.get_reconciliation_stock_details(submit) or []
if not rec_stock_detail:
msgprint("Please Check Remarks", raise_exception=1)
count = 1
for stock in rec_stock_detail:
count += 1
# Get qty as per system
cur_stock_detail = self.get_current_stock(stock[self.label['item_code']],stock[self.label['warehouse']])
stock.append(cur_stock_detail['stock_uom'])
stock.append(cur_stock_detail['actual_qty'])
# Qty Diff between file and system
diff = flt(stock[self.label['qty']]) - flt(cur_stock_detail['actual_qty'])
# Update MAR
if not stock[self.label['mar']] == '~':
self.update_mar(stock, diff)
# Make sl entry if qty differ
if diff:
self.make_sl_entry(submit, stock, diff)
if rec_stock_detail:
text = "Stock Reconciliation Completed Successfully..."
self.add_data_in_CSV(rec_stock_detail)
self.add_remark(text,'Completed', 0)
# Get csv data
#--------------------------
def get_csv_file_data(self):
filename = self.doc.file_list.split(',')
if not filename:
msgprint("Please Attach File. ", raise_exception=1)
from webnotes.utils import file_manager
fn, content = file_manager.get_file(filename[1])
if not type(content) == str:
content = content.tostring()
return content
def getCSVelement(self,v):
v = cstr(v)
if not v: return ''
if (',' in v) or ('' in v) or ('"' in v):
if '"' in v: v = v.replace('"', '""')
return '"'+v+'"'
else: return v or ''
# Add qty diff column in attached file
#----------------------------------------
def add_data_in_CSV(self,data):
filename = self.doc.file_list.split(',')
head = []
for h in ['Item Code','Warehouse','Qty','Actual','Difference','MAR']:
head.append(self.getCSVelement(h))
dset = (','.join(head) + "\n")
for d in data:
l = [d[self.label['item_code']],d[self.label['warehouse']],d[self.label['qty']],d[self.label['actual_qty']],flt(d[self.label['qty']])-flt(d[self.label['actual_qty']]),d[self.label['mar']]]
s =[]
for i in l:
s.append(self.getCSVelement(i))
dset +=(','.join(s)+"\n")
from webnotes.utils import file_manager
file_manager.write_file(filename[1], dset)
# ----------
# on submit
# ----------
def on_submit(self):
self.stock_reconciliations(submit = 1)

View File

@@ -0,0 +1,603 @@
[
{
'_last_update': '1301391552',
'allow_attach': 1,
'allow_copy': None,
'allow_email': None,
'allow_print': None,
'allow_rename': None,
'allow_trash': None,
'autoname': None,
'change_log': None,
'client_script': None,
'client_script_core': None,
'client_string': None,
'colour': 'White:FFF',
'creation': '2010-08-08 17:09:26',
'description': None,
'docstatus': 0,
'doctype': 'DocType',
'document_type': None,
'dt_template': None,
'hide_heading': None,
'hide_toolbar': None,
'idx': None,
'in_create': None,
'in_dialog': None,
'is_transaction_doc': None,
'issingle': None,
'istable': None,
'max_attachments': 1,
'menu_index': None,
'modified': '2011-04-25 11:46:21',
'modified_by': 'Administrator',
'module': 'Material Management',
'name': 'Stock Reconciliation',
'name_case': None,
'owner': 'Administrator',
'parent': None,
'parent_node': None,
'parentfield': None,
'parenttype': None,
'print_outline': None,
'read_only': None,
'read_only_onload': None,
'search_fields': 'reconciliation_date',
'section_style': 'Tray',
'server_code': None,
'server_code_compiled': None,
'server_code_core': None,
'server_code_error': ' ',
'show_in_menu': 0,
'smallicon': None,
'use_template': None,
'version': 85
},
{
'amend': 1,
'cancel': 1,
'create': 1,
'creation': '2010-08-08 17:09:26',
'docstatus': 0,
'doctype': 'DocPerm',
'execute': None,
'idx': 1,
'match': None,
'modified': '2011-04-25 11:46:21',
'modified_by': 'Administrator',
'name': 'PERM00557',
'owner': 'Administrator',
'parent': 'Stock Reconciliation',
'parentfield': 'permissions',
'parenttype': 'DocType',
'permlevel': 0,
'read': 1,
'role': 'Material Manager',
'submit': 1,
'write': 1
},
{
'amend': 0,
'cancel': 0,
'create': 0,
'creation': '2010-08-08 17:09:26',
'docstatus': 0,
'doctype': 'DocPerm',
'execute': None,
'idx': 2,
'match': None,
'modified': '2011-04-25 11:46:21',
'modified_by': 'Administrator',
'name': 'PERM00558',
'owner': 'Administrator',
'parent': 'Stock Reconciliation',
'parentfield': 'permissions',
'parenttype': 'DocType',
'permlevel': 1,
'read': 1,
'role': 'Material Manager',
'submit': 0,
'write': 0
},
{
'amend': 1,
'cancel': 1,
'create': 1,
'creation': '2010-08-08 17:09:26',
'docstatus': 0,
'doctype': 'DocPerm',
'execute': None,
'idx': 3,
'match': None,
'modified': '2011-04-25 11:46:21',
'modified_by': 'Administrator',
'name': 'PERM00559',
'owner': 'jai@webnotestech.com',
'parent': 'Stock Reconciliation',
'parentfield': 'permissions',
'parenttype': 'DocType',
'permlevel': 0,
'read': 1,
'role': 'Administrator',
'submit': 1,
'write': 1
},
{
'amend': None,
'cancel': None,
'create': None,
'creation': '2011-04-25 11:46:21',
'docstatus': 0,
'doctype': 'DocPerm',
'execute': None,
'idx': 4,
'match': None,
'modified': '2011-04-25 11:46:21',
'modified_by': 'Administrator',
'name': '000002610',
'owner': 'Administrator',
'parent': 'Stock Reconciliation',
'parentfield': 'permissions',
'parenttype': 'DocType',
'permlevel': 1,
'read': 1,
'role': 'Administrator',
'submit': None,
'write': None
},
{
'allow_on_submit': None,
'colour': None,
'creation': '2010-08-08 17:09:26',
'default': None,
'depends_on': None,
'description': None,
'docstatus': 0,
'doctype': 'DocField',
'fieldname': None,
'fieldtype': 'Button',
'hidden': 1,
'icon': None,
'idx': 1,
'in_filter': None,
'label': 'Validate Data',
'modified': '2011-04-25 11:46:21',
'modified_by': 'Administrator',
'name': 'FL03440',
'no_copy': None,
'oldfieldname': None,
'oldfieldtype': 'Button',
'options': 'get_reconciliation_stock_details',
'owner': 'Administrator',
'parent': 'Stock Reconciliation',
'parentfield': 'fields',
'parenttype': 'DocType',
'permlevel': 0,
'print_hide': None,
'report_hide': None,
'reqd': None,
'search_index': None,
'trigger': None,
'width': None
},
{
'allow_on_submit': None,
'colour': None,
'creation': '2010-08-08 17:09:26',
'default': None,
'depends_on': None,
'description': None,
'docstatus': 0,
'doctype': 'DocField',
'fieldname': None,
'fieldtype': 'Section Break',
'hidden': None,
'icon': None,
'idx': 2,
'in_filter': None,
'label': 'Summary',
'modified': '2011-04-25 11:46:21',
'modified_by': 'Administrator',
'name': 'FL03441',
'no_copy': None,
'oldfieldname': None,
'oldfieldtype': 'Section Break',
'options': None,
'owner': 'Administrator',
'parent': 'Stock Reconciliation',
'parentfield': 'fields',
'parenttype': 'DocType',
'permlevel': 0,
'print_hide': None,
'report_hide': None,
'reqd': None,
'search_index': None,
'trigger': None,
'width': None
},
{
'allow_on_submit': None,
'colour': None,
'creation': '2010-08-08 17:09:26',
'default': None,
'depends_on': None,
'description': None,
'docstatus': 0,
'doctype': 'DocField',
'fieldname': 'reconciliation_date',
'fieldtype': 'Date',
'hidden': None,
'icon': None,
'idx': 3,
'in_filter': 0,
'label': 'Reconciliation Date',
'modified': '2011-04-25 11:46:21',
'modified_by': 'Administrator',
'name': 'FL03442',
'no_copy': None,
'oldfieldname': 'reconciliation_date',
'oldfieldtype': 'Date',
'options': None,
'owner': 'Administrator',
'parent': 'Stock Reconciliation',
'parentfield': 'fields',
'parenttype': 'DocType',
'permlevel': 0,
'print_hide': None,
'report_hide': None,
'reqd': 1,
'search_index': None,
'trigger': None,
'width': None
},
{
'allow_on_submit': None,
'colour': None,
'creation': '2010-08-08 17:09:26',
'default': None,
'depends_on': None,
'description': None,
'docstatus': 0,
'doctype': 'DocField',
'fieldname': 'reconciliation_time',
'fieldtype': 'Time',
'hidden': None,
'icon': None,
'idx': 4,
'in_filter': 0,
'label': 'Reconciliation Time',
'modified': '2011-04-25 11:46:21',
'modified_by': 'Administrator',
'name': 'FL03443',
'no_copy': None,
'oldfieldname': 'reconciliation_time',
'oldfieldtype': 'Time',
'options': None,
'owner': 'nabin@webnotestech.com',
'parent': 'Stock Reconciliation',
'parentfield': 'fields',
'parenttype': 'DocType',
'permlevel': 0,
'print_hide': None,
'report_hide': None,
'reqd': 1,
'search_index': None,
'trigger': None,
'width': None
},
{
'allow_on_submit': None,
'colour': None,
'creation': '2010-08-08 17:09:26',
'default': None,
'depends_on': None,
'description': None,
'docstatus': 0,
'doctype': 'DocField',
'fieldname': 'next_step',
'fieldtype': 'Select',
'hidden': None,
'icon': None,
'idx': 5,
'in_filter': None,
'label': 'Next Steps',
'modified': '2011-04-25 11:46:21',
'modified_by': 'Administrator',
'name': 'FL03444',
'no_copy': None,
'oldfieldname': 'next_step',
'oldfieldtype': 'Select',
'options': 'Upload File and Save Document\nValidate Data\nSubmit Document\nCompleted',
'owner': 'Administrator',
'parent': 'Stock Reconciliation',
'parentfield': 'fields',
'parenttype': 'DocType',
'permlevel': 1,
'print_hide': None,
'report_hide': None,
'reqd': None,
'search_index': None,
'trigger': None,
'width': None
},
{
'allow_on_submit': None,
'colour': None,
'creation': '2010-08-08 17:09:26',
'default': None,
'depends_on': None,
'description': None,
'docstatus': 0,
'doctype': 'DocField',
'fieldname': 'remark',
'fieldtype': 'Text',
'hidden': None,
'icon': None,
'idx': 6,
'in_filter': None,
'label': 'Remark',
'modified': '2011-04-25 11:46:21',
'modified_by': 'Administrator',
'name': 'FL03445',
'no_copy': None,
'oldfieldname': 'remark',
'oldfieldtype': 'Text',
'options': None,
'owner': 'Administrator',
'parent': 'Stock Reconciliation',
'parentfield': 'fields',
'parenttype': 'DocType',
'permlevel': 1,
'print_hide': None,
'report_hide': None,
'reqd': None,
'search_index': None,
'trigger': None,
'width': None
},
{
'allow_on_submit': None,
'colour': None,
'creation': '2010-08-08 17:09:26',
'default': None,
'depends_on': None,
'description': None,
'docstatus': 0,
'doctype': 'DocField',
'fieldname': 'company',
'fieldtype': 'Link',
'hidden': None,
'icon': None,
'idx': 7,
'in_filter': 1,
'label': 'Company',
'modified': '2011-04-25 11:46:21',
'modified_by': 'Administrator',
'name': 'FL03446',
'no_copy': None,
'oldfieldname': 'company',
'oldfieldtype': 'Link',
'options': 'Company',
'owner': 'Administrator',
'parent': 'Stock Reconciliation',
'parentfield': 'fields',
'parenttype': 'DocType',
'permlevel': 0,
'print_hide': None,
'report_hide': None,
'reqd': None,
'search_index': 1,
'trigger': None,
'width': None
},
{
'allow_on_submit': None,
'colour': None,
'creation': '2010-08-08 17:09:26',
'default': None,
'depends_on': None,
'description': None,
'docstatus': 0,
'doctype': 'DocField',
'fieldname': 'fiscal_year',
'fieldtype': 'Select',
'hidden': None,
'icon': None,
'idx': 8,
'in_filter': 1,
'label': 'Fiscal Year',
'modified': '2011-04-25 11:46:21',
'modified_by': 'Administrator',
'name': 'FL03447',
'no_copy': None,
'oldfieldname': 'fiscal_year',
'oldfieldtype': 'Select',
'options': 'link:Fiscal Year',
'owner': 'Administrator',
'parent': 'Stock Reconciliation',
'parentfield': 'fields',
'parenttype': 'DocType',
'permlevel': 0,
'print_hide': None,
'report_hide': None,
'reqd': None,
'search_index': 1,
'trigger': None,
'width': None
},
{
'allow_on_submit': None,
'colour': None,
'creation': '2011-03-29 15:08:58',
'default': None,
'depends_on': None,
'description': None,
'docstatus': 0,
'doctype': 'DocField',
'fieldname': 'amended_from',
'fieldtype': 'Data',
'hidden': None,
'icon': None,
'idx': 9,
'in_filter': None,
'label': 'Amended From',
'modified': '2011-04-25 11:46:21',
'modified_by': 'Administrator',
'name': '000001851',
'no_copy': None,
'oldfieldname': None,
'oldfieldtype': None,
'options': None,
'owner': 'Administrator',
'parent': 'Stock Reconciliation',
'parentfield': 'fields',
'parenttype': 'DocType',
'permlevel': 1,
'print_hide': None,
'report_hide': None,
'reqd': None,
'search_index': None,
'trigger': None,
'width': None
},
{
'allow_on_submit': None,
'colour': None,
'creation': '2011-03-29 15:08:58',
'default': None,
'depends_on': None,
'description': None,
'docstatus': 0,
'doctype': 'DocField',
'fieldname': 'amendment_date',
'fieldtype': 'Date',
'hidden': None,
'icon': None,
'idx': 10,
'in_filter': None,
'label': 'Amendment Date',
'modified': '2011-04-25 11:46:21',
'modified_by': 'Administrator',
'name': '000001852',
'no_copy': None,
'oldfieldname': None,
'oldfieldtype': None,
'options': None,
'owner': 'Administrator',
'parent': 'Stock Reconciliation',
'parentfield': 'fields',
'parenttype': 'DocType',
'permlevel': 1,
'print_hide': None,
'report_hide': None,
'reqd': None,
'search_index': None,
'trigger': None,
'width': None
},
{
'allow_on_submit': None,
'colour': None,
'creation': '2010-08-08 17:09:26',
'default': None,
'depends_on': None,
'description': None,
'docstatus': 0,
'doctype': 'DocField',
'fieldname': None,
'fieldtype': 'Section Break',
'hidden': None,
'icon': None,
'idx': 11,
'in_filter': None,
'label': 'Attachment',
'modified': '2011-04-25 11:46:21',
'modified_by': 'Administrator',
'name': 'FL03448',
'no_copy': None,
'oldfieldname': None,
'oldfieldtype': 'Section Break',
'options': None,
'owner': 'Administrator',
'parent': 'Stock Reconciliation',
'parentfield': 'fields',
'parenttype': 'DocType',
'permlevel': 0,
'print_hide': None,
'report_hide': None,
'reqd': None,
'search_index': None,
'trigger': None,
'width': None
},
{
'allow_on_submit': None,
'colour': None,
'creation': '2010-08-08 17:09:26',
'default': None,
'depends_on': None,
'description': None,
'docstatus': 0,
'doctype': 'DocField',
'fieldname': None,
'fieldtype': 'HTML',
'hidden': None,
'icon': None,
'idx': 12,
'in_filter': None,
'label': 'Attachment HTML',
'modified': '2011-04-25 11:46:21',
'modified_by': 'Administrator',
'name': 'FL03449',
'no_copy': None,
'oldfieldname': None,
'oldfieldtype': 'HTML',
'options': 'The attachment must be a CSV(Comma Seperated Value) file',
'owner': 'Administrator',
'parent': 'Stock Reconciliation',
'parentfield': 'fields',
'parenttype': 'DocType',
'permlevel': 1,
'print_hide': None,
'report_hide': None,
'reqd': None,
'search_index': None,
'trigger': None,
'width': None
},
{
'allow_on_submit': None,
'colour': None,
'creation': '2010-08-08 17:09:26',
'default': None,
'depends_on': None,
'description': None,
'docstatus': 0,
'doctype': 'DocField',
'fieldname': 'file_list',
'fieldtype': 'Text',
'hidden': 1,
'icon': None,
'idx': 13,
'in_filter': None,
'label': 'File List',
'modified': '2011-04-25 11:46:21',
'modified_by': 'Administrator',
'name': 'FL03451',
'no_copy': None,
'oldfieldname': 'file_list',
'oldfieldtype': 'Text',
'options': None,
'owner': 'Administrator',
'parent': 'Stock Reconciliation',
'parentfield': 'fields',
'parenttype': 'DocType',
'permlevel': 1,
'print_hide': 1,
'report_hide': None,
'reqd': None,
'search_index': None,
'trigger': None,
'width': None
}
]

View File

@@ -0,0 +1,10 @@
cur_frm.fields_dict['item_code'].get_query = function(doc) {
return 'SELECT DISTINCT `tabItem`.`name`, `tabItem`.description FROM `tabItem` WHERE (IFNULL(`tabItem`.`end_of_life`,"") = "" OR `tabItem`.`end_of_life` ="0000-00-00" OR `tabItem`.`end_of_life` > NOW()) AND `tabItem`.`%(key)s` like "%s" ORDER BY `tabItem`.`name` LIMIT 50';
}
//==================== Get Items Stock UOM =====================================================
cur_frm.cscript.item_code = function(doc,cdt,cdn) {
if (doc.item_code) {
get_server_fields('get_stock_uom', doc.item_code, '', doc, cdt, cdn, 1);
}
}

View File

@@ -0,0 +1,105 @@
# Please edit this list and import only required elements
import webnotes
from webnotes.utils import add_days, add_months, add_years, cint, cstr, date_diff, default_fields, flt, fmt_money, formatdate, generate_hash, getTraceback, get_defaults, get_first_day, get_last_day, getdate, has_common, month_name, now, nowdate, replace_newlines, sendmail, set_default, str_esc_quote, user_format, validate_email_add
from webnotes.model import db_exists
from webnotes.model.doc import Document, addchild, removechild, getchildren, make_autoname, SuperDocType
from webnotes.model.doclist import getlist, copy_doclist
from webnotes.model.code import get_obj, get_server_obj, run_server_obj, updatedb, check_syntax
from webnotes import session, form, is_testing, msgprint, errprint
set = webnotes.conn.set
sql = webnotes.conn.sql
get_value = webnotes.conn.get_value
in_transaction = webnotes.conn.in_transaction
convert_to_lists = webnotes.conn.convert_to_lists
# -----------------------------------------------------------------------------------------
class DocType:
def __init__(self, d, dl=[]):
self.doc, self.doclist = d,dl
def get_stock_uom(self, item_code):
return cstr({'current_stock_uom': cstr(get_value('Item', item_code, 'stock_uom'))})
def validate_mandatory(self):
if not cstr(self.doc.item_code):
msgprint("Please Enter an Item.")
raise Exception
if not cstr(self.doc.current_stock_uom):
msgprint("There is no Current Stock UOM for Item Code" + cstr(self.doc.item_code))
raise Exception
if not cstr(self.doc.new_stock_uom):
msgprint("Please Enter New Stock UOM.")
raise Exception
if cstr(self.doc.current_stock_uom) == cstr(self.doc.new_stock_uom):
msgprint("Current Stock UOM and Stock UOM are same.")
raise Exception
# check conversion factor
if not flt(self.doc.conversion_factor):
msgprint("Please Enter Conversion Factor.")
raise Exception
stock_uom = sql("select stock_uom from `tabItem` where name = '%s'" % self.doc.item_code)
stock_uom = stock_uom and stock_uom[0][0]
if cstr(self.doc.new_stock_uom) == cstr(stock_uom):
msgprint("Item Master is already updated with New Stock UOM " + cstr(self.doc.new_stock_uom))
raise Exception
def update_item_master(self):
# update stock uom in item master
sql("update `tabItem` set stock_uom = '%s' where name = '%s' " % (self.doc.new_stock_uom, self.doc.item_code))
# acknowledge user
msgprint("New Stock UOM : " + cstr(self.doc.new_stock_uom) + " updated in Item : " + cstr(self.doc.item_code))
def update_bin(self):
# update bin
if flt(self.doc.conversion_factor) != flt(1):
sql("update `tabBin` set stock_uom = '%s' , indented_qty = ifnull(indented_qty,0) * %s, ordered_qty = ifnull(ordered_qty,0) * %s, reserved_qty = ifnull(reserved_qty,0) * %s, planned_qty = ifnull(planned_qty,0) * %s, projected_qty = actual_qty + ordered_qty + indented_qty + planned_qty - reserved_qty where item_code = '%s'" % (self.doc.new_stock_uom, self.doc.conversion_factor, self.doc.conversion_factor, self.doc.conversion_factor, self.doc.conversion_factor, self.doc.item_code) )
else:
sql("update `tabBin` set stock_uom = '%s' where item_code = '%s'" % (self.doc.new_stock_uom, self.doc.item_code) )
# acknowledge user
msgprint(" All Bin's Updated Successfully.")
def update_stock_ledger_entry(self):
# update stock ledger entry
if flt(self.doc.conversion_factor) != flt(1):
sql("update `tabStock Ledger Entry` set stock_uom = '%s', actual_qty = ifnull(actual_qty,0) * '%s' where item_code = '%s' " % (self.doc.new_stock_uom, self.doc.conversion_factor, self.doc.item_code))
else:
sql("update `tabStock Ledger Entry` set stock_uom = '%s' where item_code = '%s' " % (self.doc.new_stock_uom, self.doc.item_code))
# acknowledge user
msgprint("Stock Ledger Entries Updated Successfully.")
# update item valuation
if flt(self.doc.conversion_factor) != flt(1):
wh = sql("select name from `tabWarehouse`")
for w in wh:
bin = sql("select name from `tabBin` where item_code = '%s' and warehouse = '%s'" % (self.doc.item_code, w[0]))
if bin and bin[0][0]:
get_obj("Bin", bin[0][0]).update_item_valuation(sle_id = '', posting_date = '', posting_time = '')
# acknowledge user
msgprint("Item Valuation Updated Successfully.")
# Update Stock UOM
def update_stock_uom(self):
# validate mandatory
self.validate_mandatory()
# update item master
self.update_item_master()
# update stock ledger entry
self.update_stock_ledger_entry()
# update bin
self.update_bin()

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1 @@
[{'section_style': 'Tray', 'is_transaction_doc': None, 'creation': '2009-03-12 12:09:44', 'search_fields': None, 'module': 'Material Management', 'doctype': 'DocType', 'change_log': None, 'print_outline': '', 'owner': 'Administrator', 'in_dialog': None, 'in_create': None, 'read_only': None, 'allow_email': None, 'dt_template': None, 'hide_heading': None, 'issingle': None, 'allow_rename': None, 'smallicon': '', 'allow_attach': None, 'show_in_menu': 0, 'max_attachments': None, 'version': 1, 'menu_index': None, 'docstatus': 0, 'allow_copy': None, 'istable': 1, 'description': None, 'parent': None, 'server_code': '', 'allow_trash': None, 'allow_print': None, 'autoname': 'UCDD/.#####', 'client_script_core': None, 'client_string': None, 'use_template': None, 'modified_by': 'saumil@webnotestech.com', 'document_type': None, 'name': 'UOM Conversion Detail', 'idx': None, 'hide_toolbar': None, 'colour': 'White:FFF', 'client_script': '', 'modified': '2010-09-20 14:06:57', 'server_code_error': ' ', 'name_case': '', 'parenttype': None, 'read_only_onload': None, 'server_code_core': None, 'server_code_compiled': None, 'parent_node': None, 'parentfield': None}, {'no_copy': None, 'oldfieldtype': 'Link', 'creation': '2009-03-12 12:09:44', 'doctype': 'DocField', 'oldfieldname': 'uom', 'owner': 'Administrator', 'reqd': None, 'in_filter': None, 'print_hide': None, 'modified_by': 'saumil@webnotestech.com', 'label': 'UOM', 'width': None, 'trigger': None, 'depends_on': None, 'docstatus': 0, 'hidden': None, 'permlevel': 0, 'description': None, 'parent': 'UOM Conversion Detail', 'search_index': None, 'allow_on_submit': None, 'icon': None, 'name': 'FL00660', 'idx': 1, 'default': None, 'colour': None, 'modified': '2009-11-04 16:21:29', 'parenttype': 'DocType', 'fieldname': 'uom', 'fieldtype': 'Link', 'options': 'UOM', 'report_hide': None, 'parentfield': 'fields'}, {'no_copy': None, 'oldfieldtype': 'Float', 'creation': '2009-03-12 12:09:44', 'doctype': 'DocField', 'oldfieldname': 'conversion_factor', 'owner': 'Administrator', 'reqd': None, 'in_filter': None, 'print_hide': None, 'modified_by': 'saumil@webnotestech.com', 'label': 'Conversion Factor', 'width': None, 'trigger': None, 'depends_on': None, 'docstatus': 0, 'hidden': None, 'permlevel': 0, 'description': None, 'parent': 'UOM Conversion Detail', 'search_index': None, 'allow_on_submit': None, 'icon': None, 'name': 'FL00661', 'idx': 2, 'default': None, 'colour': None, 'modified': '2009-11-04 16:21:29', 'parenttype': 'DocType', 'fieldname': 'conversion_factor', 'fieldtype': 'Float', 'options': None, 'report_hide': None, 'parentfield': 'fields'}]

View File

@@ -0,0 +1,90 @@
# Please edit this list and import only required elements
import webnotes
from webnotes.utils import add_days, add_months, add_years, cint, cstr, date_diff, default_fields, flt, fmt_money, formatdate, generate_hash, getTraceback, get_defaults, get_first_day, get_last_day, getdate, has_common, month_name, now, nowdate, replace_newlines, sendmail, set_default, str_esc_quote, user_format, validate_email_add
from webnotes.model import db_exists
from webnotes.model.doc import Document, addchild, removechild, getchildren, make_autoname, SuperDocType
from webnotes.model.doclist import getlist, copy_doclist
from webnotes.model.code import get_obj, get_server_obj, run_server_obj, updatedb, check_syntax
from webnotes import session, form, is_testing, msgprint, errprint
set = webnotes.conn.set
sql = webnotes.conn.sql
get_value = webnotes.conn.get_value
in_transaction = webnotes.conn.in_transaction
convert_to_lists = webnotes.conn.convert_to_lists
# -----------------------------------------------------------------------------------------
class DocType:
def __init__(self, d, dl):
self.doc, self.doclist = d, dl
# Get FIFO Rate from Stack
# -------------------------
def get_fifo_rate(self, fcfs_bal, qty):
if qty:
fcfs_val = 0
withdraw = flt(qty)
while withdraw:
if not fcfs_bal:
break # nothing in store
batch = fcfs_bal[0]
if batch[0] < withdraw:
# not enough in current batch, clear batch
withdraw -= batch[0]
fcfs_val += (flt(batch[0]) * flt(batch[1]))
fcfs_bal.pop(0)
else:
# all from current batch
fcfs_val += (flt(withdraw) * flt(batch[1]))
batch[0] -= withdraw
withdraw = 0
fcfs_rate = flt(fcfs_val) / flt(qty)
return fcfs_rate
else:
return fcfs_bal and fcfs_bal[0][1] or 0
# --------------------------------
# get serializable inventory rate
# --------------------------------
def get_serializable_inventory_rate(self, serial_no):
sr_nos = get_obj("Stock Ledger").get_sr_no_list(serial_no)
tot = 0
for s in sr_nos:
serial_no = s.strip()
tot += flt(get_value('Serial No', serial_no, 'purchase_rate'))
return tot / len(sr_nos)
# ---------------------
# get valuation method
# ---------------------
def get_valuation_method(self, item_code):
val_method = webnotes.conn.get_value('Item', item_code, 'valuation_method')
if not val_method:
val_method = get_defaults().get('valuation_method', 'FIFO')
return val_method
# Get Incoming Rate based on valuation method
# --------------------------------------------
def get_incoming_rate(self, posting_date, posting_time, item, warehouse, qty = 0, serial_no = ''):
in_rate = 0
val_method = self.get_valuation_method(item)
if serial_no:
in_rate = self.get_serializable_inventory_rate(serial_no)
elif val_method == 'FIFO':
bin_obj = get_obj('Warehouse',warehouse).get_bin(item)
prev_sle = bin_obj.get_prev_sle('',posting_date, posting_time)
fcfs_stack = eval(prev_sle.get('fcfs_stack', '[]') or '[]')
in_rate = fcfs_stack and self.get_fifo_rate(fcfs_stack, qty) or 0
elif val_method == 'Moving Average':
bin_obj = get_obj('Warehouse',warehouse).get_bin(item)
prev_sle = bin_obj.get_prev_sle('',posting_date, posting_time)
in_rate = prev_sle and prev_sle.get('valuation_rate', 0) or 0
return in_rate

View File

@@ -0,0 +1 @@
[{'section_style': 'Simple', 'is_transaction_doc': None, 'creation': '2010-07-21 10:40:01', 'search_fields': None, 'module': 'Material Management', 'doctype': 'DocType', 'change_log': None, 'print_outline': '', 'owner': 'Administrator', 'in_dialog': None, 'in_create': 1, 'read_only': None, 'allow_email': None, 'dt_template': None, 'hide_heading': None, 'issingle': 1, 'allow_rename': None, 'smallicon': None, 'allow_attach': None, 'show_in_menu': None, 'max_attachments': None, 'version': 4, 'menu_index': None, 'docstatus': 0, 'allow_copy': None, 'istable': None, 'description': None, 'parent': None, 'server_code': None, 'allow_trash': None, 'allow_print': None, 'autoname': None, 'client_script_core': None, 'client_string': None, 'use_template': None, 'modified_by': 'Administrator', 'document_type': None, 'name': 'Valuation Control', 'idx': None, 'hide_toolbar': None, 'colour': 'White:FFF', 'client_script': None, 'modified': '2010-09-20 14:06:57', 'server_code_error': ' ', 'name_case': '', 'parenttype': None, 'read_only_onload': None, 'server_code_core': None, 'server_code_compiled': None, 'parent_node': None, 'parentfield': None}]

View File

@@ -0,0 +1,13 @@
cur_frm.cscript.country = function(doc, cdt, cdn) {
var mydoc=doc;
$c('runserverobj', args={'method':'check_state', 'docs':compress_doclist([doc])},
function(r,rt){
if(r.message) {
var doc = locals[mydoc.doctype][mydoc.name];
doc.state = '';
get_field(doc.doctype, 'state' , doc.name).options = r.message;
refresh_field('state');
}
}
);
}

View File

@@ -0,0 +1,90 @@
# Please edit this list and import only required elements
import webnotes
from webnotes.utils import add_days, add_months, add_years, cint, cstr, date_diff, default_fields, flt, fmt_money, formatdate, generate_hash, getTraceback, get_defaults, get_first_day, get_last_day, getdate, has_common, month_name, now, nowdate, replace_newlines, sendmail, set_default, str_esc_quote, user_format, validate_email_add
from webnotes.model import db_exists
from webnotes.model.doc import Document, addchild, removechild, getchildren, make_autoname, SuperDocType
from webnotes.model.doclist import getlist, copy_doclist
from webnotes.model.code import get_obj, get_server_obj, run_server_obj, updatedb, check_syntax
from webnotes import session, form, is_testing, msgprint, errprint
set = webnotes.conn.set
sql = webnotes.conn.sql
get_value = webnotes.conn.get_value
in_transaction = webnotes.conn.in_transaction
convert_to_lists = webnotes.conn.convert_to_lists
# -----------------------------------------------------------------------------------------
class DocType:
def __init__(self, doc, doclist=[]):
self.doc = doc
self.doclist = doclist
def get_bin(self, item_code):
bin = sql("select name from tabBin where item_code = '%s' and warehouse = '%s'" % (item_code, self.doc.name))
bin = bin and bin[0][0] or ''
if not bin:
if not self.doc.warehouse_type :
msgprint("[Warehouse Type is Mandatory] Please Enter warehouse type in Warehouse " + self.doc.name)
raise Exception
bin = Document('Bin')
bin.item_code = item_code
bin.stock_uom = get_value('Item', item_code, 'stock_uom')
bin.warehouse = self.doc.name
bin.warehouse_type = self.doc.warehouse_type
bin_obj = get_obj(doc=bin)
bin_obj.validate()
bin.save(1)
bin = bin.name
else:
bin_obj = get_obj('Bin',bin)
return bin_obj
def validate_asset(self, item_code):
if sql("select is_asset_item from tabItem where name=%s", item_code)[0][0] == 'Yes' and self.doc.warehouse_type != 'Fixed Asset':
msgprint("Fixed Asset Item %s can only be transacted in a Fixed Asset type Warehouse" % item_code)
raise Exception
# update bin
# ----------
def update_bin(self, actual_qty, reserved_qty, ordered_qty, indented_qty, planned_qty, item_code, dt, sle_id = '',posting_time = '', serial_no = ''):
self.validate_asset(item_code)
it_det = get_value('Item', item_code, 'is_stock_item')
if it_det and it_det == 'Yes':
bin = self.get_bin(item_code)
bin.update_stock(actual_qty, reserved_qty, ordered_qty, indented_qty, planned_qty, dt, sle_id, posting_time, serial_no)
return bin
else:
msgprint("[Stock Update] Ignored %s since it is not a stock item" % item_code)
# repost stock
# ------------
def repost_stock(self):
bl = sql("select name from tabBin where warehouse=%s", self.doc.name)
for b in bl:
bobj = get_obj('Bin',b[0])
bobj.update_item_valuation()
sql("COMMIT")
sql("START TRANSACTION")
def check_state(self):
return "\n" + "\n".join([i[0] for i in sql("select state_name from `tabState` where `tabState`.country='%s' " % self.doc.country)])
def validate(self):
if self.doc.email_id:
if not validate_email_add(self.doc.email_id):
msgprint("Please enter valid Email Id.")
raise Exception
if not self.doc.warehouse_type:
msgprint("[Warehouse Type is Mandatory] Please Enter Please Entry warehouse type in Warehouse " + self.doc.name)
raise Exception
wt = sql("select warehouse_type from `tabWarehouse` where name ='%s'" % self.doc.name)
if cstr(self.doc.warehouse_type) != cstr(wt and wt[0][0] or ''):
sql("update `tabStock Ledger Entry` set warehouse_type = '%s' where warehouse = '%s'" % (self.doc.warehouse_type, self.doc.name))
msgprint("All Stock Ledger Entries Updated.")

File diff suppressed because one or more lines are too long

View File

View File

@@ -0,0 +1,3 @@
report.customize_filters = function() {
this.filter_fields_dict['Item'+FILTER_SEP +'ID'].df.in_first_page = 1;
}

View File

@@ -0,0 +1,37 @@
[
{
'add_col': None,
'add_cond': None,
'add_tab': None,
'columns': 'Item\x01Item Name,Item\x01Item Group,Ref Rate Detail\x01Price List Name,Ref Rate Detail\x01Ref Rate,Ref Rate Detail\x01Currency',
'creation': '2010-08-20 12:20:55',
'criteria_name': 'Itemwise Price List',
'custom_query': '',
'description': None,
'dis_filters': None,
'disabled': None,
'doc_type': 'Ref Rate Detail',
'docstatus': 0,
'doctype': 'Search Criteria',
'filters': "{'Item\x01Saved':1,'Ref Rate Detail\x01Price List Name':'','Ref Rate Detail\x01Currency':''}",
'graph_series': None,
'graph_values': None,
'group_by': None,
'idx': None,
'modified': '2010-08-20 12:15:17',
'modified_by': 'Administrator',
'module': 'Material Management',
'name': 'itemwise_price_list',
'owner': 'harshada@webnotestech.com',
'page_len': 50,
'parent': None,
'parent_doc_type': 'Item',
'parentfield': None,
'parenttype': None,
'report_script': None,
'server_script': None,
'sort_by': '`tabItem`.`item_name`',
'sort_order': 'DESC',
'standard': 'Yes'
}
]

View File

@@ -0,0 +1,11 @@
report.customize_filters = function() {
this.add_filter({fieldname:'posting_date', label:'Posting Date', fieldtype:'Date', ignore : 1, parent:'Item'});
//this.add_filter({fieldname:'weekly_working_days', label:'Weekly Working Days', fieldtype:'Select', options:NEWLINE+1+NEWLINE+2+NEWLINE+3+NEWLINE+4+NEWLINE+5+NEWLINE+6+NEWLINE+7, ignore : 1, parent:'Item'});
this.filter_fields_dict['Item'+FILTER_SEP +'From Posting Date'].df.in_first_page = 1;
this.filter_fields_dict['Item'+FILTER_SEP +'To Posting Date'].df.in_first_page = 1;
//this.filter_fields_dict['Item'+FILTER_SEP +'Weekly Working Days'].df.in_first_page = 1;
}

View File

@@ -0,0 +1,132 @@
mon_list = []
data = {'start_date':0, 'end_date':1, 'working_days': 2}
def make_month_list(start_date, end_date, mon_list, colnames, coltypes, colwidths, coloptions, col_idx):
# get period between from date and to date
period_diff = sql("select PERIOD_DIFF('%s','%s')"% (('').join( end_date.split('-')[i] for i in range(len(end_date.split('-')) - 1)),('').join(start_date.split('-')[i] for i in range(len(start_date.split('-')) - 1))))
period_diff = period_diff and int(period_diff[0][0])
for pd in range(int(period_diff) + 1):
# get last date
last_date = str(sql("select LAST_DAY('%s')" % start_date)[0][0])
# get no of days in the month
if not int(sql("select DATEDIFF('%s','%s')" % (end_date, last_date))[0][0]) >0:
last_date = end_date
diff = int(sql("select DATEDIFF('%s','%s')" % (last_date, start_date))[0][0]) + 1
# make mon_list
mon_list.append([start_date, last_date, (diff > 26) and 26 or diff])
# add months as Column names
month_name = sql("select MONTHNAME('%s')" % start_date)[0][0]
colnames.append(str(str(month_name)[:3])+ '-'+ str(start_date[:4]))
coltypes.append('Currency')
colwidths.append('150px')
coloptions.append('')
col_idx[str(str(month_name)[:3])+ '-'+ str(start_date[:4])] = len(colnames) - 1
# get start date
start_date = str(sql("select DATE_ADD('%s',INTERVAL 1 DAY)" % last_date)[0][0])
# Validation for 'ID' and 'Lead Time Days' Column Name
if 'ID' not in colnames or 'Lead Time Days' not in colnames:
msgprint("Please select Id and Lead Time Days in 'Select Columns' tab Else Report will not be generated")
raise Exception
# Validation for Posting Date Filters
if not filter_values.get('posting_date') or not filter_values.get('posting_date1'):
msgprint("Please select From Posting Date and To Posting Date")
raise Exception
else:
from_date = str(filter_values.get('posting_date'))
to_date = str(filter_values.get('posting_date1'))
# Call Make Month List Function
make_month_list(from_date, to_date, mon_list, colnames, coltypes, colwidths, coloptions, col_idx)
# Add Column names
col = [['Total Daily Consumption','Currency','150px','']
,['MIL(Min Inv. Level)','Currency','150px','']
,['ROL(Re-Order Level)','Currency','150px','']
,['Actual Quantity','Currency','150px','']
,['Indented Quantity','Currency','150px','']
,['Ordered Quantity','Currency','150px','']
,['Shortage To Indent','Currency','150px','']
,['MAR','Currency','100px','']
,['LPR','Currency','100px','']]
for c in col:
colnames.append(c[0])
coltypes.append(c[1])
colwidths.append(c[2])
coloptions.append(c[3])
col_idx[c[0]] = len(colnames) - 1
for r in res:
# calculate Total Daily Consumption Monthly
count, tot_consumption, tot_days = 0, 0, 1
#for idx in range(col_idx['Stock Unit of Measurement'] + 1 , col_idx['Total Daily Consumption'] ):
for idx in range(col_idx['Lead Time Days'] + 1 , col_idx['Total Daily Consumption'] ):
# As Consumption Means:= Adding Qty Transfered to WIP Warehouse ++ Qty Issued directly warehouse whose waraehouse_type != WIP Warehouse and Subtracting Qty Issued from WIP Warehouse
#Capture item qty coming to WIP Warehouse for production purpose which means consuming that items
add_con = sql("select ifnull(sum(t1.actual_qty),0) from `tabStock Ledger Entry` t1 where t1.item_code = '%s' and t1.is_cancelled = 'No' and t1.posting_date >= '%s' and t1.posting_date <= '%s' and t1.warehouse_type = 'WIP Warehouse' and t1.actual_qty > 0 " % (r[col_idx['ID']],mon_list[count][data['start_date']],mon_list[count][data['end_date']]))
# This is Stock Entry which is of Type Material Issue also to mention that Source Warehouse should not be WIP WArehouse
#Transfering items to Internal Other Warehouse but not to WIP Warehouse
dir_con = sql("select ifnull(sum(t1.actual_qty),0) from `tabStock Ledger Entry` t1, `tabStock Entry Detail` t2 where t1.item_code = '%s' and t1.is_cancelled = 'No' and t1.posting_date >= '%s' and t1.posting_date <= '%s' and t1.warehouse_type != 'WIP Warehouse' and t1.actual_qty < 0 and t1.voucher_type = 'Stock Entry' and t1.voucher_detail_no = t2.name and ifnull(t2.t_warehouse, '') = ''"%(r[col_idx['ID']],mon_list[count][data['start_date']],mon_list[count][data['end_date']]))
# This is Stock Entry which is of Type MAterial TRansfer also to mention that Source Warehouse should be WIP WArhouse
#like, transfering items from internal warehouse to customer
red_con = sql("select ifnull(sum(t1.actual_qty),0) from `tabStock Ledger Entry` t1, `tabStock Entry Detail` t2 where t1.item_code = '%s' and t1.is_cancelled = 'No' and t1.posting_date >= '%s' and t1.posting_date <= '%s' and t1.warehouse_type = 'WIP Warehouse' and t1.actual_qty < 0 and t1.voucher_type = 'Stock Entry' and t1.voucher_detail_no = t2.name and ifnull(t2.t_warehouse, '') != ''"%(r[col_idx['ID']],mon_list[count][data['start_date']],mon_list[count][data['end_date']]))
#msgprint(str(add_con[0][0]) + "~~~" + str(dir_con[0][0]) + "~~~" + str(red_con[0][0]))
add_con = add_con and add_con[0][0] or 0.00
dir_con = dir_con and ((-1) * dir_con[0][0]) or 0.00
red_con = red_con and red_con[0][0] or 0.00
tot_con = flt(add_con) + flt(dir_con) + flt(red_con)
#tot_con = add_con and add_con[0][0] or 0 + dir_con and (-1) * dir_con[0][0] or 0 + red_con and red_con[0][0] or 0
tot_con = flt(r[col_idx['Lead Time Days']] and tot_con or 0)
# monthly avg consumption
r.append(flt(tot_con / mon_list[count][data['working_days']]))
# calculate tot_consumption and tot_days
tot_consumption = flt(tot_consumption) + flt(tot_con)
tot_days = (tot_days == 1) and flt(mon_list[count][data['working_days']]) or (flt(tot_days) + flt(mon_list[count][data['working_days']]))
count = count + 1
# Calculate Daily Consumption
r.append(tot_consumption and flt(tot_consumption /tot_days) or 0)
# Calculate Minimum Inventory Level
r.append(flt(r[col_idx['Total Daily Consumption']]) * flt(r[col_idx['Lead Time Days']]))
# Calculate Re-Order Level
r.append(flt(r[col_idx['MIL(Min Inv. Level)']] * 2))
# get stock level
stock_level = sql("select sum(t1.actual_qty), sum(t1.indented_qty), sum(t1.ordered_qty) from `tabBin` t1, `tabWarehouse` t2 where t1.warehouse = t2.name and t2.warehouse_type != 'WIP Warehouse' and t1.item_code = '%s'"%(r[col_idx['ID']]))
r.append(stock_level and flt(stock_level[0][0]) or 0) # Actual Qty
r.append(stock_level and flt(stock_level[0][1]) or 0) # Indented Qty
r.append(stock_level and flt(stock_level[0][2]) or 0) # Ordered Qty
# calculate shortage
r.append((r[col_idx['ROL(Re-Order Level)']] > 0) and flt(flt(r[col_idx['ROL(Re-Order Level)']]) - flt(r[col_idx['Actual Quantity']]) - flt(r[col_idx['Indented Quantity']]) - flt(r[col_idx['Ordered Quantity']])) or 0)
# get moving average rate
m_a_r = sql("select ifnull(sum(t1.ma_rate), 0)/ ifnull(count(t1.name),1) from `tabBin` t1, `tabWarehouse` t2 where t1.item_code = '%s' and ifnull(t1.ma_rate, 0) > 0 and t1.warehouse = t2.name and t2.warehouse_type != 'WIP Warehouse'" % r[col_idx['ID']])
r.append(m_a_r and flt(m_a_r[0][0]) or 0)
# get recent last purchase rate
lpr_rate = flt(sql("select last_purchase_rate from `tabItem` where name = '%s'" %r[col_idx['ID']])[0][0]) or 0.00
r.append(lpr_rate)

View File

@@ -0,0 +1,37 @@
[
{
'add_col': None,
'add_cond': None,
'add_tab': None,
'columns': 'Item\x01ID,Item\x01Item Name,Item\x01Description,Item\x01Lead Time Days',
'creation': '2011-05-25 12:44:22',
'criteria_name': 'Shortage To Indent',
'custom_query': '',
'description': None,
'dis_filters': None,
'disabled': None,
'doc_type': 'Item',
'docstatus': 0,
'doctype': 'Search Criteria',
'filters': "{'Item\x01Saved':1}",
'graph_series': None,
'graph_values': None,
'group_by': None,
'idx': None,
'modified': '2011-05-18 11:52:59',
'modified_by': 'Guest',
'module': 'Material Management',
'name': 'shortage_to_indent',
'owner': 'wasim@webnotestech.com',
'page_len': 50,
'parent': None,
'parent_doc_type': None,
'parentfield': None,
'parenttype': None,
'report_script': None,
'server_script': None,
'sort_by': '`tabItem`.`name`',
'sort_order': 'DESC',
'standard': 'Yes'
}
]

View File

@@ -0,0 +1,12 @@
report.customize_filters = function() {
//this.hide_all_filters();
this.filter_fields_dict['Serial No'+FILTER_SEP +'Status'].df.filter_hide = 1;
this.filter_fields_dict['Serial No'+FILTER_SEP +'ID'].df.in_first_page = 1;
this.filter_fields_dict['Serial No'+FILTER_SEP +'From Purchase Date'].df.in_first_page = 1;
this.filter_fields_dict['Serial No'+FILTER_SEP +'To Purchase Date'].df.in_first_page = 1;
}
//this.mytabs.items['Select Columns'].hide();
this.mytabs.items['More Filters'].hide();

Some files were not shown because too many files have changed in this diff Show More