\ No newline at end of file
diff --git a/erpnext/accounts/doctype/process_statement_of_accounts/process_statement_of_accounts.js b/erpnext/accounts/doctype/process_statement_of_accounts/process_statement_of_accounts.js
index 7425132c468..088c190f451 100644
--- a/erpnext/accounts/doctype/process_statement_of_accounts/process_statement_of_accounts.js
+++ b/erpnext/accounts/doctype/process_statement_of_accounts/process_statement_of_accounts.js
@@ -19,7 +19,7 @@ frappe.ui.form.on('Process Statement Of Accounts', {
frappe.show_alert({message: __('Emails Queued'), indicator: 'blue'});
}
else{
- frappe.msgprint('No Records for these settings.')
+ frappe.msgprint(__('No Records for these settings.'))
}
}
});
@@ -33,7 +33,7 @@ frappe.ui.form.on('Process Statement Of Accounts', {
type: 'GET',
success: function(result) {
if(jQuery.isEmptyObject(result)){
- frappe.msgprint('No Records for these settings.');
+ frappe.msgprint(__('No Records for these settings.'));
}
else{
window.location = url;
@@ -92,7 +92,7 @@ frappe.ui.form.on('Process Statement Of Accounts', {
frm.refresh_field('customers');
}
else{
- frappe.msgprint('No Customers found with selected options.');
+ frappe.throw(__('No Customers found with selected options.'));
}
}
}
@@ -129,4 +129,4 @@ frappe.ui.form.on('Process Statement Of Accounts Customer', {
}
})
}
-});
\ No newline at end of file
+});
diff --git a/erpnext/accounts/doctype/process_statement_of_accounts/process_statement_of_accounts.json b/erpnext/accounts/doctype/process_statement_of_accounts/process_statement_of_accounts.json
index 4be0e2ec068..27a5f50ce2a 100644
--- a/erpnext/accounts/doctype/process_statement_of_accounts/process_statement_of_accounts.json
+++ b/erpnext/accounts/doctype/process_statement_of_accounts/process_statement_of_accounts.json
@@ -1,6 +1,5 @@
{
"actions": [],
- "allow_workflow": 1,
"autoname": "Prompt",
"creation": "2020-05-22 16:46:18.712954",
"doctype": "DocType",
@@ -28,9 +27,11 @@
"customers",
"preferences",
"orientation",
- "section_break_14",
"include_ageing",
"ageing_based_on",
+ "section_break_14",
+ "letter_head",
+ "terms_and_conditions",
"section_break_1",
"enable_auto_email",
"section_break_18",
@@ -270,10 +271,22 @@
"fieldname": "body",
"fieldtype": "Text Editor",
"label": "Body"
+ },
+ {
+ "fieldname": "letter_head",
+ "fieldtype": "Link",
+ "label": "Letter Head",
+ "options": "Letter Head"
+ },
+ {
+ "fieldname": "terms_and_conditions",
+ "fieldtype": "Link",
+ "label": "Terms and Conditions",
+ "options": "Terms and Conditions"
}
],
"links": [],
- "modified": "2020-08-08 08:47:09.185728",
+ "modified": "2021-05-21 10:14:22.426672",
"modified_by": "Administrator",
"module": "Accounts",
"name": "Process Statement Of Accounts",
diff --git a/erpnext/accounts/doctype/process_statement_of_accounts/process_statement_of_accounts.py b/erpnext/accounts/doctype/process_statement_of_accounts/process_statement_of_accounts.py
index d50e4a8af95..500952e38ad 100644
--- a/erpnext/accounts/doctype/process_statement_of_accounts/process_statement_of_accounts.py
+++ b/erpnext/accounts/doctype/process_statement_of_accounts/process_statement_of_accounts.py
@@ -4,10 +4,12 @@
from __future__ import unicode_literals
import frappe
+from frappe import _
from frappe.model.document import Document
from erpnext.accounts.report.general_ledger.general_ledger import execute as get_soa
from erpnext.accounts.report.accounts_receivable_summary.accounts_receivable_summary import execute as get_ageing
-from frappe.core.doctype.communication.email import make
+from erpnext import get_company_currency
+from erpnext.accounts.party import get_party_account_currency
from frappe.utils.print_format import report_to_pdf
from frappe.utils.pdf import get_pdf
@@ -29,7 +31,7 @@ class ProcessStatementOfAccounts(Document):
validate_template(self.body)
if not self.customers:
- frappe.throw(frappe._('Customers not selected.'))
+ frappe.throw(_('Customers not selected.'))
if self.enable_auto_email:
self.to_date = self.start_date
@@ -38,7 +40,7 @@ class ProcessStatementOfAccounts(Document):
def get_report_pdf(doc, consolidated=True):
statement_dict = {}
- aging = ''
+ ageing = ''
base_template_path = "frappe/www/printview.html"
template_path = "erpnext/accounts/doctype/process_statement_of_accounts/process_statement_of_accounts.html"
@@ -54,26 +56,33 @@ def get_report_pdf(doc, consolidated=True):
'range4': 120,
'customer': entry.customer
})
- col1, aging = get_ageing(ageing_filters)
- aging[0]['ageing_based_on'] = doc.ageing_based_on
+ col1, ageing = get_ageing(ageing_filters)
+
+ if ageing:
+ ageing[0]['ageing_based_on'] = doc.ageing_based_on
tax_id = frappe.get_doc('Customer', entry.customer).tax_id
+ presentation_currency = get_party_account_currency('Customer', entry.customer, doc.company) \
+ or doc.currency or get_company_currency(doc.company)
+ if doc.letter_head:
+ from frappe.www.printview import get_letter_head
+ letter_head = get_letter_head(doc, 0)
filters= frappe._dict({
'from_date': doc.from_date,
'to_date': doc.to_date,
'company': doc.company,
'finance_book': doc.finance_book if doc.finance_book else None,
- "account": doc.account if doc.account else None,
+ 'account': doc.account if doc.account else None,
'party_type': 'Customer',
'party': [entry.customer],
+ 'presentation_currency': presentation_currency,
'group_by': doc.group_by,
'currency': doc.currency,
'cost_center': [cc.cost_center_name for cc in doc.cost_center],
'project': [p.project_name for p in doc.project],
'show_opening_entries': 0,
'include_default_book_entries': 0,
- 'show_cancelled_entries': 1,
'tax_id': tax_id if tax_id else None
})
col, res = get_soa(filters)
@@ -83,11 +92,17 @@ def get_report_pdf(doc, consolidated=True):
if len(res) == 3:
continue
+
html = frappe.render_template(template_path, \
- {"filters": filters, "data": res, "aging": aging[0] if doc.include_ageing else None})
+ {"filters": filters, "data": res, "ageing": ageing[0] if (doc.include_ageing and ageing) else None,
+ "letter_head": letter_head if doc.letter_head else None,
+ "terms_and_conditions": frappe.db.get_value('Terms and Conditions', doc.terms_and_conditions, 'terms')
+ if doc.terms_and_conditions else None})
+
html = frappe.render_template(base_template_path, {"body": html, \
"css": get_print_style(), "title": "Statement For " + entry.customer})
statement_dict[entry.customer] = html
+
if not bool(statement_dict):
return False
elif consolidated:
@@ -126,9 +141,11 @@ def get_customers_based_on_sales_person(sales_person):
sales_person_records = frappe._dict()
for d in records:
sales_person_records.setdefault(d.parenttype, set()).add(d.parent)
- customers = frappe.get_list('Customer', fields=['name', 'email_id'], \
+ if sales_person_records.get('Customer'):
+ return frappe.get_list('Customer', fields=['name', 'email_id'], \
filters=[['name', 'in', list(sales_person_records['Customer'])]])
- return customers
+ else:
+ return []
def get_recipients_and_cc(customer, doc):
recipients = []
@@ -165,7 +182,7 @@ def fetch_customers(customer_collection, collection_name, primary_mandatory):
if customer_collection == 'Sales Person':
customers = get_customers_based_on_sales_person(collection_name)
if not bool(customers):
- frappe.throw('No Customers found with selected options.')
+ frappe.throw(_('No Customers found with selected options.'))
else:
if customer_collection == 'Sales Partner':
customers = frappe.get_list('Customer', fields=['name', 'email_id'], \
@@ -190,21 +207,20 @@ def fetch_customers(customer_collection, collection_name, primary_mandatory):
@frappe.whitelist()
def get_customer_emails(customer_name, primary_mandatory, billing_and_primary=True):
billing_email = frappe.db.sql("""
- SELECT c.email_id FROM `tabContact` AS c JOIN `tabDynamic Link` AS l ON c.name=l.parent \
- WHERE l.link_doctype='Customer' and l.link_name='""" + customer_name + """' and \
- c.is_billing_contact=1 \
- order by c.creation desc""")
+ SELECT c.email_id FROM `tabContact` AS c JOIN `tabDynamic Link` AS l ON c.name=l.parent
+ WHERE l.link_doctype='Customer' and l.link_name=%s and c.is_billing_contact=1
+ order by c.creation desc""", customer_name)
if len(billing_email) == 0 or (billing_email[0][0] is None):
if billing_and_primary:
- frappe.throw('No billing email found for customer: '+ customer_name)
+ frappe.throw(_("No billing email found for customer: {0}").format(customer_name))
else:
return ''
if billing_and_primary:
primary_email = frappe.get_value('Customer', customer_name, 'email_id')
if primary_email is None and int(primary_mandatory):
- frappe.throw('No primary email found for customer: '+ customer_name)
+ frappe.throw(_("No primary email found for customer: {0}").format(customer_name))
return [primary_email or '', billing_email[0][0]]
else:
return billing_email[0][0] or ''
diff --git a/erpnext/accounts/doctype/promotional_scheme/promotional_scheme.py b/erpnext/accounts/doctype/promotional_scheme/promotional_scheme.py
index 523e9ee08ae..7d9302382f1 100644
--- a/erpnext/accounts/doctype/promotional_scheme/promotional_scheme.py
+++ b/erpnext/accounts/doctype/promotional_scheme/promotional_scheme.py
@@ -9,7 +9,7 @@ from frappe.utils import cstr
from frappe.model.naming import make_autoname
from frappe.model.document import Document
-pricing_rule_fields = ['apply_on', 'mixed_conditions', 'is_cumulative', 'other_item_code', 'other_item_group'
+pricing_rule_fields = ['apply_on', 'mixed_conditions', 'is_cumulative', 'other_item_code', 'other_item_group',
'apply_rule_on_other', 'other_brand', 'selling', 'buying', 'applicable_for', 'valid_from',
'valid_upto', 'customer', 'customer_group', 'territory', 'sales_partner', 'campaign', 'supplier',
'supplier_group', 'company', 'currency', 'apply_multiple_pricing_rules']
@@ -111,4 +111,4 @@ def get_args_for_pricing_rule(doc):
for d in pricing_rule_fields:
args[d] = doc.get(d)
- return args
\ No newline at end of file
+ return args
diff --git a/erpnext/accounts/doctype/purchase_invoice/purchase_invoice.js b/erpnext/accounts/doctype/purchase_invoice/purchase_invoice.js
index 66a8e206a81..dc9094c3e91 100644
--- a/erpnext/accounts/doctype/purchase_invoice/purchase_invoice.js
+++ b/erpnext/accounts/doctype/purchase_invoice/purchase_invoice.js
@@ -27,10 +27,6 @@ erpnext.accounts.PurchaseInvoice = erpnext.buying.BuyingController.extend({
});
},
- company: function() {
- erpnext.accounts.dimensions.update_dimension(this.frm, this.frm.doctype);
- },
-
onload: function() {
this._super();
@@ -496,15 +492,6 @@ cur_frm.fields_dict['items'].grid.get_field('project').get_query = function(doc,
}
}
-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 Invoice");
-}
-
frappe.ui.form.on("Purchase Invoice", {
setup: function(frm) {
frm.custom_make_buttons = {
@@ -523,6 +510,28 @@ frappe.ui.form.on("Purchase Invoice", {
}
},
+ refresh: function(frm) {
+ frm.events.add_custom_buttons(frm);
+ },
+
+ add_custom_buttons: function(frm) {
+ if (frm.doc.per_received < 100) {
+ frm.add_custom_button(__('Purchase Receipt'), () => {
+ frm.events.make_purchase_receipt(frm);
+ }, __('Create'));
+ }
+
+ if (frm.doc.docstatus == 1 && frm.doc.per_received > 0) {
+ frm.add_custom_button(__('Purchase Receipt'), () => {
+ frappe.route_options = {
+ 'purchase_invoice': frm.doc.name
+ }
+
+ frappe.set_route("List", "Purchase Receipt", "List")
+ }, __('View'));
+ }
+ },
+
onload: function(frm) {
if(frm.doc.__onload && frm.is_new()) {
if(frm.doc.supplier) {
@@ -548,5 +557,17 @@ frappe.ui.form.on("Purchase Invoice", {
update_stock: function(frm) {
hide_fields(frm.doc);
frm.fields_dict.items.grid.toggle_reqd("item_code", frm.doc.update_stock? true: false);
- }
+ },
+
+ make_purchase_receipt: function(frm) {
+ frappe.model.open_mapped_doc({
+ method: "erpnext.accounts.doctype.purchase_invoice.purchase_invoice.make_purchase_receipt",
+ frm: frm,
+ freeze_message: __("Creating Purchase Receipt ...")
+ })
+ },
+
+ company: function(frm) {
+ erpnext.accounts.dimensions.update_dimension(frm, frm.doctype);
+ },
})
diff --git a/erpnext/accounts/doctype/purchase_invoice/purchase_invoice.json b/erpnext/accounts/doctype/purchase_invoice/purchase_invoice.json
index 18b66375e99..00ef7d5c184 100644
--- a/erpnext/accounts/doctype/purchase_invoice/purchase_invoice.json
+++ b/erpnext/accounts/doctype/purchase_invoice/purchase_invoice.json
@@ -127,7 +127,6 @@
"write_off_cost_center",
"advances_section",
"allocate_advances_automatically",
- "adjust_advance_taxes",
"get_advances",
"advances",
"payment_schedule_section",
@@ -164,7 +163,8 @@
"to_date",
"column_break_114",
"auto_repeat",
- "update_auto_repeat_reference"
+ "update_auto_repeat_reference",
+ "per_received"
],
"fields": [
{
@@ -592,11 +592,12 @@
"label": "Raw Materials Supplied"
},
{
+ "depends_on": "update_stock",
"fieldname": "supplied_items",
"fieldtype": "Table",
"label": "Supplied Items",
- "options": "Purchase Receipt Item Supplied",
- "read_only": 1
+ "no_copy": 1,
+ "options": "Purchase Receipt Item Supplied"
},
{
"fieldname": "section_break_26",
@@ -837,6 +838,7 @@
"read_only": 1
},
{
+ "depends_on": "eval:!doc.disable_rounded_total",
"fieldname": "base_rounding_adjustment",
"fieldtype": "Currency",
"label": "Rounding Adjustment (Company Currency)",
@@ -883,6 +885,7 @@
"read_only": 1
},
{
+ "depends_on": "eval:!doc.disable_rounded_total",
"fieldname": "rounding_adjustment",
"fieldtype": "Currency",
"label": "Rounding Adjustment",
@@ -1326,13 +1329,6 @@
"label": "Project",
"options": "Project"
},
- {
- "default": "0",
- "description": "Taxes paid while advance payment will be adjusted against this invoice",
- "fieldname": "adjust_advance_taxes",
- "fieldtype": "Check",
- "label": "Adjust Advance Taxes"
- },
{
"depends_on": "eval:doc.is_internal_supplier",
"description": "Unrealized Profit / Loss account for intra-company transfers",
@@ -1372,13 +1368,22 @@
"print_hide": 1,
"print_width": "50px",
"width": "50px"
+ },
+ {
+ "fieldname": "per_received",
+ "fieldtype": "Percent",
+ "hidden": 1,
+ "label": "Per Received",
+ "no_copy": 1,
+ "print_hide": 1,
+ "read_only": 1
}
],
"icon": "fa fa-file-text",
"idx": 204,
"is_submittable": 1,
"links": [],
- "modified": "2021-03-09 21:12:30.422084",
+ "modified": "2021-06-15 18:20:56.806195",
"modified_by": "Administrator",
"module": "Accounts",
"name": "Purchase Invoice",
diff --git a/erpnext/accounts/doctype/purchase_invoice/purchase_invoice.py b/erpnext/accounts/doctype/purchase_invoice/purchase_invoice.py
index 5c4e32e493e..f7992797ed4 100644
--- a/erpnext/accounts/doctype/purchase_invoice/purchase_invoice.py
+++ b/erpnext/accounts/doctype/purchase_invoice/purchase_invoice.py
@@ -68,9 +68,6 @@ class PurchaseInvoice(BuyingController):
super(PurchaseInvoice, self).validate()
- # apply tax withholding only if checked and applicable
- self.set_tax_withholding()
-
if not self.is_return:
self.po_required()
self.pr_required()
@@ -251,11 +248,9 @@ class PurchaseInvoice(BuyingController):
if self.update_stock and (not item.from_warehouse):
if for_validate and item.expense_account and item.expense_account != warehouse_account[item.warehouse]["account"]:
- msg = _("Row {}: Expense Head changed to {} ").format(item.idx, frappe.bold(warehouse_account[item.warehouse]["account"]))
- msg += _("because account {} is not linked to warehouse {} ").format(frappe.bold(item.expense_account), frappe.bold(item.warehouse))
- msg += _("or it is not the default inventory account")
+ msg = _("Row {0}: Expense Head changed to {1} because account {2} is not linked to warehouse {3} or it is not the default inventory account").format(
+ item.idx, frappe.bold(warehouse_account[item.warehouse]["account"]), frappe.bold(item.expense_account), frappe.bold(item.warehouse))
frappe.msgprint(msg, title=_("Expense Head Changed"))
-
item.expense_account = warehouse_account[item.warehouse]["account"]
else:
# check if 'Stock Received But Not Billed' account is credited in Purchase receipt or not
@@ -266,8 +261,8 @@ class PurchaseInvoice(BuyingController):
if negative_expense_booked_in_pr:
if for_validate and item.expense_account and item.expense_account != stock_not_billed_account:
- msg = _("Row {}: Expense Head changed to {} ").format(item.idx, frappe.bold(stock_not_billed_account))
- msg += _("because expense is booked against this account in Purchase Receipt {}").format(frappe.bold(item.purchase_receipt))
+ msg = _("Row {0}: Expense Head changed to {1} because expense is booked against this account in Purchase Receipt {2}").format(
+ item.idx, frappe.bold(stock_not_billed_account), frappe.bold(item.purchase_receipt))
frappe.msgprint(msg, title=_("Expense Head Changed"))
item.expense_account = stock_not_billed_account
@@ -275,8 +270,9 @@ class PurchaseInvoice(BuyingController):
# If no purchase receipt present then book expense in 'Stock Received But Not Billed'
# This is done in cases when Purchase Invoice is created before Purchase Receipt
if for_validate and item.expense_account and item.expense_account != stock_not_billed_account:
- msg = _("Row {}: Expense Head changed to {} ").format(item.idx, frappe.bold(stock_not_billed_account))
- msg += _("as no Purchase Receipt is created against Item {}. ").format(frappe.bold(item.item_code))
+ msg = _("Row {0}: Expense Head changed to {1} as no Purchase Receipt is created against Item {2}.").format(
+ item.idx, frappe.bold(stock_not_billed_account), frappe.bold(item.item_code))
+ msg += " "
msg += _("This is done to handle accounting for cases when Purchase Receipt is created after Purchase Invoice")
frappe.msgprint(msg, title=_("Expense Head Changed"))
@@ -308,8 +304,8 @@ class PurchaseInvoice(BuyingController):
if not d.purchase_order:
msg = _("Purchase Order Required for item {}").format(frappe.bold(d.item_code))
msg += "
"
- msg += _("To submit the invoice without purchase order please set {} ").format(frappe.bold(_('Purchase Order Required')))
- msg += _("as {} in {}").format(frappe.bold('No'), get_link_to_form('Buying Settings', 'Buying Settings', 'Buying Settings'))
+ msg += _("To submit the invoice without purchase order please set {0} as {1} in {2}").format(
+ frappe.bold(_('Purchase Order Required')), frappe.bold('No'), get_link_to_form('Buying Settings', 'Buying Settings', 'Buying Settings'))
throw(msg, title=_("Mandatory Purchase Order"))
def pr_required(self):
@@ -323,8 +319,8 @@ class PurchaseInvoice(BuyingController):
if not d.purchase_receipt and d.item_code in stock_items:
msg = _("Purchase Receipt Required for item {}").format(frappe.bold(d.item_code))
msg += "
\n {% set start = frappe.utils.get_datetime(doc.start_time) %}\n {% set end = frappe.utils.get_datetime(doc.end_time) %}\n {% if start.date() == end.date() %}\n
\n {% set start = frappe.utils.get_datetime(doc.start_time) %}\n {% set end = frappe.utils.get_datetime(doc.end_time) %}\n {% if start.date() == end.date() %}\n
\n\t\t{%- for row in doc.taxes -%}\n\t\t {%- if (not row.included_in_print_rate or doc.flags.show_inclusive_tax_in_print) and row.tax_amount != 0 -%}\n\t\t\t
\n\t\t\t\t
\n\t\t\t\t\t{% if '%' in row.description %}\n\t\t\t\t\t {{ row.description }}\n\t\t\t\t\t{% else %}\n\t\t\t\t\t {{ row.description }}@{{ row.rate }}%\n\t\t\t\t\t{% endif %}\n\t\t\t\t
\n\t\t{%- for row in doc.taxes -%}\n\t\t {%- if (not row.included_in_print_rate or doc.flags.show_inclusive_tax_in_print) and row.tax_amount != 0 -%}\n\t\t\t
\n\t\t\t\t
\n\t\t\t\t\t{% if '%' in row.description %}\n\t\t\t\t\t {{ row.description }}\n\t\t\t\t\t{% else %}\n\t\t\t\t\t {{ row.description }}@{{ row.rate }}%\n\t\t\t\t\t{% endif %}\n\t\t\t\t
'
-}
-
// TODO: validate gross weight field
diff --git a/erpnext/stock/doctype/packing_slip/packing_slip.py b/erpnext/stock/doctype/packing_slip/packing_slip.py
index 2008bffcd32..4a843e0fde9 100644
--- a/erpnext/stock/doctype/packing_slip/packing_slip.py
+++ b/erpnext/stock/doctype/packing_slip/packing_slip.py
@@ -88,9 +88,9 @@ class PackingSlip(Document):
rows = [d.item_code for d in self.get("items")]
# also pick custom fields from delivery note
- custom_fields = ', '.join(['dni.`{0}`'.format(d.fieldname)
+ custom_fields = ', '.join('dni.`{0}`'.format(d.fieldname)
for d in frappe.get_meta("Delivery Note Item").get_custom_fields()
- if d.fieldtype not in no_value_fields])
+ if d.fieldtype not in no_value_fields)
if custom_fields:
custom_fields = ', ' + custom_fields
diff --git a/erpnext/stock/doctype/pick_list/pick_list.json b/erpnext/stock/doctype/pick_list/pick_list.json
index c01388dcd21..21467935370 100644
--- a/erpnext/stock/doctype/pick_list/pick_list.json
+++ b/erpnext/stock/doctype/pick_list/pick_list.json
@@ -184,4 +184,4 @@
"sort_field": "modified",
"sort_order": "DESC",
"track_changes": 1
-}
\ No newline at end of file
+}
diff --git a/erpnext/stock/doctype/pick_list/pick_list.py b/erpnext/stock/doctype/pick_list/pick_list.py
index 755fa615bb0..516ae43089b 100644
--- a/erpnext/stock/doctype/pick_list/pick_list.py
+++ b/erpnext/stock/doctype/pick_list/pick_list.py
@@ -17,6 +17,9 @@ from erpnext.selling.doctype.sales_order.sales_order import make_delivery_note a
# TODO: Prioritize SO or WO group warehouse
class PickList(Document):
+ def validate(self):
+ self.validate_for_qty()
+
def before_save(self):
self.set_item_locations()
@@ -35,6 +38,7 @@ class PickList(Document):
@frappe.whitelist()
def set_item_locations(self, save=False):
+ self.validate_for_qty()
items = self.aggregate_item_qty()
self.item_location_map = frappe._dict()
@@ -107,6 +111,11 @@ class PickList(Document):
return item_map.values()
+ def validate_for_qty(self):
+ if self.purpose == "Material Transfer for Manufacture" \
+ and (self.for_qty is None or self.for_qty == 0):
+ frappe.throw(_("Qty of Finished Goods Item should be greater than 0."))
+
def validate_item_locations(pick_list):
if not pick_list.locations:
@@ -230,6 +239,7 @@ def get_available_item_locations_for_batched_item(item_code, from_warehouses, re
and sle.`item_code`=%(item_code)s
and sle.`company` = %(company)s
and batch.disabled = 0
+ and sle.is_cancelled=0
and IFNULL(batch.`expiry_date`, '2200-01-01') > %(today)s
{warehouse_condition}
GROUP BY
@@ -379,7 +389,6 @@ def create_stock_entry(pick_list):
else:
stock_entry = update_stock_entry_items_with_no_reference(pick_list, stock_entry)
- stock_entry.set_incoming_rate()
stock_entry.set_actual_qty()
stock_entry.calculate_rate_and_amount()
diff --git a/erpnext/stock/doctype/pick_list/test_pick_list.py b/erpnext/stock/doctype/pick_list/test_pick_list.py
index c4da05a6d44..84566b8d8c7 100644
--- a/erpnext/stock/doctype/pick_list/test_pick_list.py
+++ b/erpnext/stock/doctype/pick_list/test_pick_list.py
@@ -37,6 +37,7 @@ class TestPickList(unittest.TestCase):
'company': '_Test Company',
'customer': '_Test Customer',
'items_based_on': 'Sales Order',
+ 'purpose': 'Delivery',
'locations': [{
'item_code': '_Test Item',
'qty': 5,
@@ -90,6 +91,7 @@ class TestPickList(unittest.TestCase):
'company': '_Test Company',
'customer': '_Test Customer',
'items_based_on': 'Sales Order',
+ 'purpose': 'Delivery',
'locations': [{
'item_code': '_Test Item Warehouse Group Wise Reorder',
'qty': 1000,
@@ -135,6 +137,7 @@ class TestPickList(unittest.TestCase):
'company': '_Test Company',
'customer': '_Test Customer',
'items_based_on': 'Sales Order',
+ 'purpose': 'Delivery',
'locations': [{
'item_code': '_Test Serialized Item',
'qty': 1000,
@@ -264,6 +267,7 @@ class TestPickList(unittest.TestCase):
'company': '_Test Company',
'customer': '_Test Customer',
'items_based_on': 'Sales Order',
+ 'purpose': 'Delivery',
'locations': [{
'item_code': '_Test Item',
'qty': 5,
@@ -319,6 +323,7 @@ class TestPickList(unittest.TestCase):
'company': '_Test Company',
'customer': '_Test Customer',
'items_based_on': 'Sales Order',
+ 'purpose': 'Delivery',
'locations': [{
'item_code': '_Test Item',
'qty': 1,
diff --git a/erpnext/stock/doctype/purchase_receipt/purchase_receipt.js b/erpnext/stock/doctype/purchase_receipt/purchase_receipt.js
index 57cc3504a90..befdad96924 100644
--- a/erpnext/stock/doctype/purchase_receipt/purchase_receipt.js
+++ b/erpnext/stock/doctype/purchase_receipt/purchase_receipt.js
@@ -73,6 +73,34 @@ frappe.ui.form.on("Purchase Receipt", {
})
}, __('Create'));
}
+
+ frm.events.add_custom_buttons(frm);
+ },
+
+ add_custom_buttons: function(frm) {
+ if (frm.doc.docstatus == 0) {
+ frm.add_custom_button(__('Purchase Invoice'), function () {
+ if (!frm.doc.supplier) {
+ frappe.throw({
+ title: __("Mandatory"),
+ message: __("Please Select a Supplier")
+ });
+ }
+ erpnext.utils.map_current_doc({
+ method: "erpnext.accounts.doctype.purchase_invoice.purchase_invoice.make_purchase_receipt",
+ source_doctype: "Purchase Invoice",
+ target: frm,
+ setters: {
+ supplier: frm.doc.supplier,
+ },
+ get_query_filters: {
+ docstatus: 1,
+ per_received: ["<", 100],
+ company: frm.doc.company
+ }
+ })
+ }, __("Get Items From"));
+ }
},
company: function(frm) {
@@ -248,13 +276,6 @@ cur_frm.fields_dict['items'].grid.get_field('project').get_query = function(doc,
}
}
-cur_frm.cscript.select_print_heading = function(doc, cdt, cdn) {
- if(doc.select_print_heading)
- cur_frm.pformat.print_heading = doc.select_print_heading;
- else
- cur_frm.pformat.print_heading = "Purchase Receipt";
-}
-
cur_frm.fields_dict['select_print_heading'].get_query = function(doc, cdt, cdn) {
return {
filters: [
diff --git a/erpnext/stock/doctype/purchase_receipt/purchase_receipt.json b/erpnext/stock/doctype/purchase_receipt/purchase_receipt.json
index 32d349f3031..44fb736304f 100755
--- a/erpnext/stock/doctype/purchase_receipt/purchase_receipt.json
+++ b/erpnext/stock/doctype/purchase_receipt/purchase_receipt.json
@@ -514,8 +514,7 @@
"oldfieldname": "pr_raw_material_details",
"oldfieldtype": "Table",
"options": "Purchase Receipt Item Supplied",
- "print_hide": 1,
- "read_only": 1
+ "print_hide": 1
},
{
"fieldname": "section_break0",
@@ -762,6 +761,7 @@
"read_only": 1
},
{
+ "depends_on": "eval:!doc.disable_rounded_total",
"fieldname": "base_rounding_adjustment",
"fieldtype": "Currency",
"label": "Rounding Adjustment (Company Currency)",
@@ -805,6 +805,7 @@
"read_only": 1
},
{
+ "depends_on": "eval:!doc.disable_rounded_total",
"fieldname": "rounding_adjustment",
"fieldtype": "Currency",
"label": "Rounding Adjustment",
@@ -1147,7 +1148,7 @@
"idx": 261,
"is_submittable": 1,
"links": [],
- "modified": "2020-12-26 20:49:39.106049",
+ "modified": "2021-05-25 00:15:12.239017",
"modified_by": "Administrator",
"module": "Stock",
"name": "Purchase Receipt",
diff --git a/erpnext/stock/doctype/purchase_receipt/purchase_receipt.py b/erpnext/stock/doctype/purchase_receipt/purchase_receipt.py
index 5d7597b2db5..82c87a83a50 100644
--- a/erpnext/stock/doctype/purchase_receipt/purchase_receipt.py
+++ b/erpnext/stock/doctype/purchase_receipt/purchase_receipt.py
@@ -53,7 +53,20 @@ class PurchaseReceipt(BuyingController):
'target_ref_field': 'stock_qty',
'source_field': 'stock_qty',
'percent_join_field': 'material_request'
+ },
+ {
+ 'source_dt': 'Purchase Receipt Item',
+ 'target_dt': 'Purchase Invoice Item',
+ 'join_field': 'purchase_invoice_item',
+ 'target_field': 'received_qty',
+ 'target_parent_dt': 'Purchase Invoice',
+ 'target_parent_field': 'per_received',
+ 'target_ref_field': 'qty',
+ 'source_field': 'received_qty',
+ 'percent_join_field': 'purchase_invoice',
+ 'overflow_type': 'receipt'
}]
+
if cint(self.is_return):
self.status_updater.extend([
{
@@ -189,6 +202,7 @@ class PurchaseReceipt(BuyingController):
self.make_gl_entries()
self.repost_future_sle_and_gle()
+ self.set_consumed_qty_in_po()
def check_next_docstatus(self):
submit_rv = frappe.db.sql("""select t1.name
@@ -220,7 +234,9 @@ class PurchaseReceipt(BuyingController):
self.repost_future_sle_and_gle()
self.ignore_linked_doctypes = ('GL Entry', 'Stock Ledger Entry', 'Repost Item Valuation')
self.delete_auto_created_batches()
+ self.set_consumed_qty_in_po()
+ @frappe.whitelist()
def get_current_stock(self):
for d in self.get('supplied_items'):
if self.supplier_warehouse:
@@ -229,16 +245,23 @@ class PurchaseReceipt(BuyingController):
def get_gl_entries(self, warehouse_account=None):
from erpnext.accounts.general_ledger import process_gl_map
+ gl_entries = []
+ self.make_item_gl_entries(gl_entries, warehouse_account=warehouse_account)
+ self.make_tax_gl_entries(gl_entries)
+ self.get_asset_gl_entry(gl_entries)
+
+ return process_gl_map(gl_entries)
+
+ def make_item_gl_entries(self, gl_entries, warehouse_account=None):
stock_rbnb = self.get_company_default("stock_received_but_not_billed")
landed_cost_entries = get_item_account_wise_additional_cost(self.name)
expenses_included_in_valuation = self.get_company_default("expenses_included_in_valuation")
auto_accounting_for_non_stock_items = cint(frappe.db.get_value('Company', self.company, 'enable_perpetual_inventory_for_non_stock_items'))
- gl_entries = []
warehouse_with_no_account = []
- negative_expense_to_be_booked = 0.0
stock_items = self.get_stock_items()
+
for d in self.get("items"):
if d.item_code in stock_items and flt(d.valuation_rate) and flt(d.qty):
if warehouse_account.get(d.warehouse):
@@ -249,21 +272,22 @@ class PurchaseReceipt(BuyingController):
if not stock_value_diff:
continue
+ warehouse_account_name = warehouse_account[d.warehouse]["account"]
+ warehouse_account_currency = warehouse_account[d.warehouse]["account_currency"]
+ supplier_warehouse_account = warehouse_account.get(self.supplier_warehouse, {}).get("account")
+ supplier_warehouse_account_currency = warehouse_account.get(self.supplier_warehouse, {}).get("account_currency")
+ remarks = self.get("remarks") or _("Accounting Entry for Stock")
+
# If PR is sub-contracted and fg item rate is zero
- # in that case if account for shource and target warehouse are same,
+ # in that case if account for source and target warehouse are same,
# then GL entries should not be posted
if flt(stock_value_diff) == flt(d.rm_supp_cost) \
and warehouse_account.get(self.supplier_warehouse) \
- and warehouse_account[d.warehouse]["account"] == warehouse_account[self.supplier_warehouse]["account"]:
+ and warehouse_account_name == supplier_warehouse_account:
continue
- gl_entries.append(self.get_gl_dict({
- "account": warehouse_account[d.warehouse]["account"],
- "against": stock_rbnb,
- "cost_center": d.cost_center,
- "remarks": self.get("remarks") or _("Accounting Entry for Stock"),
- "debit": stock_value_diff
- }, warehouse_account[d.warehouse]["account_currency"], item=d))
+ self.add_gl_entry(gl_entries, warehouse_account_name, d.cost_center, stock_value_diff, 0.0, remarks,
+ stock_rbnb, account_currency=warehouse_account_currency, item=d)
# GL Entry for from warehouse or Stock Received but not billed
# Intentionally passed negative debit amount to avoid incorrect GL Entry validation
@@ -273,43 +297,28 @@ class PurchaseReceipt(BuyingController):
credit_amount = flt(d.base_net_amount, d.precision("base_net_amount")) \
if credit_currency == self.company_currency else flt(d.net_amount, d.precision("net_amount"))
if credit_amount:
- gl_entries.append(self.get_gl_dict({
- "account": warehouse_account[d.from_warehouse]['account'] \
- if d.from_warehouse else stock_rbnb,
- "against": warehouse_account[d.warehouse]["account"],
- "cost_center": d.cost_center,
- "remarks": self.get("remarks") or _("Accounting Entry for Stock"),
- "debit": -1 * flt(d.base_net_amount, d.precision("base_net_amount")),
- "debit_in_account_currency": -1 * credit_amount
- }, credit_currency, item=d))
+ account = warehouse_account[d.from_warehouse]['account'] \
+ if d.from_warehouse else stock_rbnb
- negative_expense_to_be_booked += flt(d.item_tax_amount)
+ self.add_gl_entry(gl_entries, account, d.cost_center,
+ -1 * flt(d.base_net_amount, d.precision("base_net_amount")), 0.0, remarks, warehouse_account_name,
+ debit_in_account_currency=-1 * credit_amount, account_currency=credit_currency, item=d)
- # Amount added through landed-cost-voucher
+ # Amount added through landed-cos-voucher
if d.landed_cost_voucher_amount and landed_cost_entries:
for account, amount in iteritems(landed_cost_entries[(d.item_code, d.name)]):
account_currency = get_account_currency(account)
- gl_entries.append(self.get_gl_dict({
- "account": account,
- "account_currency": account_currency,
- "against": warehouse_account[d.warehouse]["account"],
- "cost_center": d.cost_center,
- "remarks": self.get("remarks") or _("Accounting Entry for Stock"),
- "credit": (flt(amount["base_amount"]) if (amount["base_amount"] or
- account_currency!=self.company_currency) else flt(amount["amount"])),
- "credit_in_account_currency": flt(amount["amount"]),
- "project": d.project
- }, item=d))
+ credit_amount = (flt(amount["base_amount"]) if (amount["base_amount"] or
+ account_currency!=self.company_currency) else flt(amount["amount"]))
+
+ self.add_gl_entry(gl_entries, account, d.cost_center, 0.0, credit_amount, remarks,
+ warehouse_account_name, credit_in_account_currency=flt(amount["amount"]),
+ account_currency=account_currency, project=d.project, item=d)
# sub-contracting warehouse
if flt(d.rm_supp_cost) and warehouse_account.get(self.supplier_warehouse):
- gl_entries.append(self.get_gl_dict({
- "account": warehouse_account[self.supplier_warehouse]["account"],
- "against": warehouse_account[d.warehouse]["account"],
- "cost_center": d.cost_center,
- "remarks": self.get("remarks") or _("Accounting Entry for Stock"),
- "credit": flt(d.rm_supp_cost)
- }, warehouse_account[self.supplier_warehouse]["account_currency"], item=d))
+ self.add_gl_entry(gl_entries, supplier_warehouse_account, d.cost_center, 0.0, flt(d.rm_supp_cost),
+ remarks, warehouse_account_name, account_currency=supplier_warehouse_account_currency, item=d)
# divisional loss adjustment
valuation_amount_as_per_doc = flt(d.base_net_amount, d.precision("base_net_amount")) + \
@@ -326,46 +335,32 @@ class PurchaseReceipt(BuyingController):
cost_center = d.cost_center or frappe.get_cached_value("Company", self.company, "cost_center")
- gl_entries.append(self.get_gl_dict({
- "account": loss_account,
- "against": warehouse_account[d.warehouse]["account"],
- "cost_center": cost_center,
- "remarks": self.get("remarks") or _("Accounting Entry for Stock"),
- "debit": divisional_loss,
- "project": d.project
- }, credit_currency, item=d))
+ self.add_gl_entry(gl_entries, loss_account, cost_center, divisional_loss, 0.0, remarks,
+ warehouse_account_name, account_currency=credit_currency, project=d.project, item=d)
elif d.warehouse not in warehouse_with_no_account or \
d.rejected_warehouse not in warehouse_with_no_account:
warehouse_with_no_account.append(d.warehouse)
elif d.item_code not in stock_items and not d.is_fixed_asset and flt(d.qty) and auto_accounting_for_non_stock_items:
-
service_received_but_not_billed_account = self.get_company_default("service_received_but_not_billed")
credit_currency = get_account_currency(service_received_but_not_billed_account)
-
- gl_entries.append(self.get_gl_dict({
- "account": service_received_but_not_billed_account,
- "against": d.expense_account,
- "cost_center": d.cost_center,
- "remarks": self.get("remarks") or _("Accounting Entry for Service"),
- "project": d.project,
- "credit": d.amount,
- "voucher_detail_no": d.name
- }, credit_currency, item=d))
-
debit_currency = get_account_currency(d.expense_account)
+ remarks = self.get("remarks") or _("Accounting Entry for Service")
- gl_entries.append(self.get_gl_dict({
- "account": d.expense_account,
- "against": service_received_but_not_billed_account,
- "cost_center": d.cost_center,
- "remarks": self.get("remarks") or _("Accounting Entry for Service"),
- "project": d.project,
- "debit": d.amount,
- "voucher_detail_no": d.name
- }, debit_currency, item=d))
+ self.add_gl_entry(gl_entries, service_received_but_not_billed_account, d.cost_center, 0.0, d.amount,
+ remarks, d.expense_account, account_currency=credit_currency, project=d.project,
+ voucher_detail_no=d.name, item=d)
- self.get_asset_gl_entry(gl_entries)
+ self.add_gl_entry(gl_entries, d.expense_account, d.cost_center, d.amount, 0.0, remarks, service_received_but_not_billed_account,
+ account_currency = debit_currency, project=d.project, voucher_detail_no=d.name, item=d)
+
+ if warehouse_with_no_account:
+ frappe.msgprint(_("No accounting entries for the following warehouses") + ": \n" +
+ "\n".join(warehouse_with_no_account))
+
+ def make_tax_gl_entries(self, gl_entries):
+ expenses_included_in_valuation = self.get_company_default("expenses_included_in_valuation")
+ negative_expense_to_be_booked = sum([flt(d.item_tax_amount) for d in self.get('items')])
# Cost center-wise amount breakup for other charges included for valuation
valuation_tax = {}
for tax in self.get("taxes"):
@@ -391,6 +386,7 @@ class PurchaseReceipt(BuyingController):
against_account = ", ".join([d.account for d in gl_entries if flt(d.debit) > 0])
total_valuation_amount = sum(valuation_tax.values())
amount_including_divisional_loss = negative_expense_to_be_booked
+ stock_rbnb = self.get_company_default("stock_received_but_not_billed")
i = 1
for tax in self.get("taxes"):
if valuation_tax.get(tax.name):
@@ -406,23 +402,33 @@ class PurchaseReceipt(BuyingController):
applicable_amount = negative_expense_to_be_booked * (valuation_tax[tax.name] / total_valuation_amount)
amount_including_divisional_loss -= applicable_amount
- gl_entries.append(
- self.get_gl_dict({
- "account": account,
- "cost_center": tax.cost_center,
- "credit": applicable_amount,
- "remarks": self.remarks or _("Accounting Entry for Stock"),
- "against": against_account
- }, item=tax)
- )
+ self.add_gl_entry(gl_entries, account, tax.cost_center, 0.0, applicable_amount, self.remarks or _("Accounting Entry for Stock"),
+ against_account, item=tax)
i += 1
- if warehouse_with_no_account:
- frappe.msgprint(_("No accounting entries for the following warehouses") + ": \n" +
- "\n".join(warehouse_with_no_account))
+ def add_gl_entry(self, gl_entries, account, cost_center, debit, credit, remarks, against_account,
+ debit_in_account_currency=None, credit_in_account_currency=None, account_currency=None,
+ project=None, voucher_detail_no=None, item=None):
+ gl_entry = {
+ "account": account,
+ "cost_center": cost_center,
+ "debit": debit,
+ "credit": credit,
+ "against_account": against_account,
+ "remarks": remarks,
+ }
- return process_gl_map(gl_entries)
+ if voucher_detail_no:
+ gl_entry.update({"voucher_detail_no": voucher_detail_no})
+
+ if debit_in_account_currency:
+ gl_entry.update({"debit_in_account_currency": debit_in_account_currency})
+
+ if credit_in_account_currency:
+ gl_entry.update({"credit_in_account_currency": credit_in_account_currency})
+
+ gl_entries.append(self.get_gl_dict(gl_entry, item=item))
def get_asset_gl_entry(self, gl_entries):
for item in self.get("items"):
@@ -444,30 +450,21 @@ class PurchaseReceipt(BuyingController):
asset_amount = flt(item.net_amount) + flt(item.item_tax_amount/self.conversion_rate)
base_asset_amount = flt(item.base_net_amount + item.item_tax_amount)
+ remarks = self.get("remarks") or _("Accounting Entry for Asset")
cwip_account_currency = get_account_currency(cwip_account)
# debit cwip account
- gl_entries.append(self.get_gl_dict({
- "account": cwip_account,
- "against": arbnb_account,
- "cost_center": item.cost_center,
- "remarks": self.get("remarks") or _("Accounting Entry for Asset"),
- "debit": base_asset_amount,
- "debit_in_account_currency": (base_asset_amount
- if cwip_account_currency == self.company_currency else asset_amount)
- }, item=item))
+ debit_in_account_currency = (base_asset_amount
+ if cwip_account_currency == self.company_currency else asset_amount)
+ self.add_gl_entry(gl_entries, cwip_account, item.cost_center, base_asset_amount, 0.0, remarks,
+ arbnb_account, debit_in_account_currency=debit_in_account_currency, item=item)
asset_rbnb_currency = get_account_currency(arbnb_account)
# credit arbnb account
- gl_entries.append(self.get_gl_dict({
- "account": arbnb_account,
- "against": cwip_account,
- "cost_center": item.cost_center,
- "remarks": self.get("remarks") or _("Accounting Entry for Asset"),
- "credit": base_asset_amount,
- "credit_in_account_currency": (base_asset_amount
- if asset_rbnb_currency == self.company_currency else asset_amount)
- }, item=item))
+ credit_in_account_currency = (base_asset_amount
+ if asset_rbnb_currency == self.company_currency else asset_amount)
+ self.add_gl_entry(gl_entries, arbnb_account, item.cost_center, 0.0, base_asset_amount, remarks,
+ cwip_account, credit_in_account_currency=credit_in_account_currency, item=item)
def add_lcv_gl_entries(self, item, gl_entries):
expenses_included_in_asset_valuation = self.get_company_default("expenses_included_in_asset_valuation")
@@ -478,23 +475,13 @@ class PurchaseReceipt(BuyingController):
# This returns company's default cwip account
asset_account = get_asset_account("capital_work_in_progress_account", company=self.company)
- gl_entries.append(self.get_gl_dict({
- "account": expenses_included_in_asset_valuation,
- "against": asset_account,
- "cost_center": item.cost_center,
- "remarks": self.get("remarks") or _("Accounting Entry for Stock"),
- "credit": flt(item.landed_cost_voucher_amount),
- "project": item.project
- }, item=item))
+ remarks = self.get("remarks") or _("Accounting Entry for Stock")
- gl_entries.append(self.get_gl_dict({
- "account": asset_account,
- "against": expenses_included_in_asset_valuation,
- "cost_center": item.cost_center,
- "remarks": self.get("remarks") or _("Accounting Entry for Stock"),
- "debit": flt(item.landed_cost_voucher_amount),
- "project": item.project
- }, item=item))
+ self.add_gl_entry(gl_entries, expenses_included_in_asset_valuation, item.cost_center, 0.0, flt(item.landed_cost_voucher_amount),
+ remarks, asset_account, project=item.project, item=item)
+
+ self.add_gl_entry(gl_entries, asset_account, item.cost_center, 0.0, flt(item.landed_cost_voucher_amount),
+ remarks, expenses_included_in_asset_valuation, project=item.project, item=item)
def update_assets(self, item, valuation_rate):
assets = frappe.db.get_all('Asset',
@@ -513,7 +500,9 @@ class PurchaseReceipt(BuyingController):
def update_billing_status(self, update_modified=True):
updated_pr = [self.name]
for d in self.get("items"):
- if d.purchase_order_item:
+ if d.get("purchase_invoice") and d.get("purchase_invoice_item"):
+ d.db_set('billed_amt', d.amount, update_modified=update_modified)
+ elif d.purchase_order_item:
updated_pr += update_billed_amount_based_on_po(d.purchase_order_item, update_modified)
for pr in set(updated_pr):
@@ -593,7 +582,6 @@ def update_billing_percentage(pr_doc, update_modified=True):
@frappe.whitelist()
def make_purchase_invoice(source_name, target_doc=None):
- from frappe.model.mapper import get_mapped_doc
from erpnext.accounts.party import get_payment_terms_template
doc = frappe.get_doc('Purchase Receipt', source_name)
@@ -613,11 +601,16 @@ def make_purchase_invoice(source_name, target_doc=None):
def update_item(source_doc, target_doc, source_parent):
target_doc.qty, returned_qty = get_pending_qty(source_doc)
+ if frappe.db.get_single_value("Buying Settings", "bill_for_rejected_quantity_in_purchase_invoice"):
+ target_doc.rejected_qty = 0
target_doc.stock_qty = flt(target_doc.qty) * flt(target_doc.conversion_factor, target_doc.precision("conversion_factor"))
returned_qty_map[source_doc.name] = returned_qty
def get_pending_qty(item_row):
- pending_qty = item_row.qty - invoiced_qty_map.get(item_row.name, 0)
+ qty = item_row.qty
+ if frappe.db.get_single_value("Buying Settings", "bill_for_rejected_quantity_in_purchase_invoice"):
+ qty = item_row.received_qty
+ pending_qty = qty - invoiced_qty_map.get(item_row.name, 0)
returned_qty = flt(returned_qty_map.get(item_row.name, 0))
if returned_qty:
if returned_qty >= pending_qty:
@@ -762,4 +755,3 @@ def get_item_account_wise_additional_cost(purchase_document):
account.base_amount * item.get(based_on_field) / total_item_cost
return item_account_wise_cost
-
diff --git a/erpnext/stock/doctype/purchase_receipt/test_purchase_receipt.py b/erpnext/stock/doctype/purchase_receipt/test_purchase_receipt.py
index 7f0c3fa8010..2eb8bfd5d2f 100644
--- a/erpnext/stock/doctype/purchase_receipt/test_purchase_receipt.py
+++ b/erpnext/stock/doctype/purchase_receipt/test_purchase_receipt.py
@@ -13,8 +13,9 @@ from erpnext.stock.doctype.serial_no.serial_no import SerialNoDuplicateError
from erpnext.accounts.doctype.account.test_account import get_inventory_account
from erpnext.stock.doctype.item.test_item import make_item
from six import iteritems
+from erpnext.stock.stock_ledger import SerialNoExistsInFutureTransaction
from erpnext.stock.doctype.warehouse.test_warehouse import create_warehouse
-
+from erpnext.stock.doctype.serial_no.serial_no import get_serial_nos
class TestPurchaseReceipt(unittest.TestCase):
def setUp(self):
@@ -144,6 +145,62 @@ class TestPurchaseReceipt(unittest.TestCase):
self.assertFalse(frappe.db.get_value('Batch', {'item': item.name, 'reference_name': pr.name}))
self.assertFalse(frappe.db.get_all('Serial No', {'batch_no': batch_no}))
+ def test_duplicate_serial_nos(self):
+ from erpnext.stock.doctype.delivery_note.test_delivery_note import create_delivery_note
+
+ item = frappe.db.exists("Item", {'item_name': 'Test Serialized Item 123'})
+ if not item:
+ item = create_item("Test Serialized Item 123")
+ item.has_serial_no = 1
+ item.serial_no_series = "TSI123-.####"
+ item.save()
+ else:
+ item = frappe.get_doc("Item", {'item_name': 'Test Serialized Item 123'})
+
+ # First make purchase receipt
+ pr = make_purchase_receipt(item_code=item.name, qty=2, rate=500)
+ pr.load_from_db()
+
+ serial_nos = frappe.db.get_value('Stock Ledger Entry',
+ {'voucher_type': 'Purchase Receipt', 'voucher_no': pr.name, 'item_code': item.name}, 'serial_no')
+
+ serial_nos = get_serial_nos(serial_nos)
+
+ self.assertEquals(get_serial_nos(pr.items[0].serial_no), serial_nos)
+
+ # Then tried to receive same serial nos in difference company
+ pr_different_company = make_purchase_receipt(item_code=item.name, qty=2, rate=500,
+ serial_no='\n'.join(serial_nos), company='_Test Company 1', do_not_submit=True,
+ warehouse = 'Stores - _TC1')
+
+ self.assertRaises(SerialNoDuplicateError, pr_different_company.submit)
+
+ # Then made delivery note to remove the serial nos from stock
+ dn = create_delivery_note(item_code=item.name, qty=2, rate = 1500, serial_no='\n'.join(serial_nos))
+ dn.load_from_db()
+ self.assertEquals(get_serial_nos(dn.items[0].serial_no), serial_nos)
+
+ posting_date = add_days(today(), -3)
+
+ # Try to receive same serial nos again in the same company with backdated.
+ pr1 = make_purchase_receipt(item_code=item.name, qty=2, rate=500,
+ posting_date=posting_date, serial_no='\n'.join(serial_nos), do_not_submit=True)
+
+ self.assertRaises(SerialNoExistsInFutureTransaction, pr1.submit)
+
+ # Try to receive same serial nos with different company with backdated.
+ pr2 = make_purchase_receipt(item_code=item.name, qty=2, rate=500,
+ posting_date=posting_date, serial_no='\n'.join(serial_nos), company='_Test Company 1', do_not_submit=True,
+ warehouse = 'Stores - _TC1')
+
+ self.assertRaises(SerialNoExistsInFutureTransaction, pr2.submit)
+
+ # Receive the same serial nos after the delivery note posting date and time
+ make_purchase_receipt(item_code=item.name, qty=2, rate=500, serial_no='\n'.join(serial_nos))
+
+ # Raise the error for backdated deliver note entry cancel
+ self.assertRaises(SerialNoExistsInFutureTransaction, dn.cancel)
+
def test_purchase_receipt_gl_entry(self):
pr = make_purchase_receipt(company="_Test Company with perpetual inventory",
warehouse = "Stores - TCP1", supplier_warehouse = "Work in Progress - TCP1",
@@ -189,7 +246,7 @@ class TestPurchaseReceipt(unittest.TestCase):
pr = make_purchase_receipt(item_code="_Test FG Item", qty=10, rate=500, is_subcontracted="Yes")
self.assertEqual(len(pr.get("supplied_items")), 2)
- rm_supp_cost = sum([d.amount for d in pr.get("supplied_items")])
+ rm_supp_cost = sum(d.amount for d in pr.get("supplied_items"))
self.assertEqual(pr.get("items")[0].rm_supp_cost, flt(rm_supp_cost, 2))
pr.cancel()
@@ -240,6 +297,8 @@ class TestPurchaseReceipt(unittest.TestCase):
item_code = "Test Extra Item 1", qty=10, basic_rate=100)
se2 = make_stock_entry(target="_Test Warehouse - _TC",
item_code = "_Test FG Item", qty=1, basic_rate=100)
+ se3 = make_stock_entry(target="_Test Warehouse - _TC",
+ item_code = "Test Extra Item 2", qty=1, basic_rate=100)
rm_items = [
{
"item_code": item_code,
@@ -274,7 +333,12 @@ class TestPurchaseReceipt(unittest.TestCase):
se.cancel()
se1.cancel()
se2.cancel()
+ se3.cancel()
po.reload()
+ pr2.load_from_db()
+ pr2.cancel()
+
+ po.load_from_db()
po.cancel()
def test_serial_no_supplier(self):
@@ -357,11 +421,18 @@ class TestPurchaseReceipt(unittest.TestCase):
self.assertEqual(return_pr_2.items[0].qty, -3)
# Make PI against unreturned amount
+ buying_settings = frappe.get_single("Buying Settings")
+ buying_settings.bill_for_rejected_quantity_in_purchase_invoice = 0
+ buying_settings.save()
+
pi = make_purchase_invoice(pr.name)
pi.submit()
self.assertEqual(pi.items[0].qty, 3)
+ buying_settings.bill_for_rejected_quantity_in_purchase_invoice = 1
+ buying_settings.save()
+
pr.load_from_db()
# PR should be completed on billing all unreturned amount
self.assertEqual(pr.items[0].billed_amt, 150)
@@ -562,29 +633,6 @@ class TestPurchaseReceipt(unittest.TestCase):
new_pr_doc.cancel()
- def test_not_accept_duplicate_serial_no(self):
- from erpnext.stock.doctype.stock_entry.test_stock_entry import make_stock_entry
- from erpnext.stock.doctype.delivery_note.test_delivery_note import create_delivery_note
-
- item_code = frappe.db.get_value('Item', {'has_serial_no': 1, 'is_fixed_asset': 0, "has_batch_no": 0})
- if not item_code:
- item = make_item("Test Serial Item 1", dict(has_serial_no=1, has_batch_no=0))
- item_code = item.name
-
- serial_no = random_string(5)
- pr1 = make_purchase_receipt(item_code=item_code, qty=1, serial_no=serial_no)
- dn = create_delivery_note(item_code=item_code, qty=1, serial_no=serial_no)
-
- pr2 = make_purchase_receipt(item_code=item_code, qty=1, serial_no=serial_no, do_not_submit=True)
- self.assertRaises(SerialNoDuplicateError, pr2.submit)
-
- se = make_stock_entry(item_code=item_code, target="_Test Warehouse - _TC", qty=1,
- serial_no=serial_no, basic_rate=100, do_not_submit=True)
- se.submit()
-
- dn.cancel()
- pr1.cancel()
-
def test_auto_asset_creation(self):
asset_item = "Test Asset Item"
@@ -619,10 +667,10 @@ class TestPurchaseReceipt(unittest.TestCase):
pr = make_purchase_receipt(item_code=asset_item, qty=3)
assets = frappe.db.get_all('Asset', filters={'purchase_receipt': pr.name})
- self.assertEquals(len(assets), 3)
+ self.assertEqual(len(assets), 3)
location = frappe.db.get_value('Asset', assets[0].name, 'location')
- self.assertEquals(location, "Test Location")
+ self.assertEqual(location, "Test Location")
pr.cancel()
@@ -727,7 +775,7 @@ class TestPurchaseReceipt(unittest.TestCase):
pr1.submit()
pi = make_purchase_invoice(pr.name)
- self.assertEquals(pi.items[0].qty, 3)
+ self.assertEqual(pi.items[0].qty, 3)
pr1.cancel()
pr.reload()
@@ -758,8 +806,8 @@ class TestPurchaseReceipt(unittest.TestCase):
pr2.submit()
pi2 = make_purchase_invoice(pr1.name)
- self.assertEquals(pi2.items[0].qty, 2)
- self.assertEquals(pi2.items[1].qty, 1)
+ self.assertEqual(pi2.items[0].qty, 2)
+ self.assertEqual(pi2.items[1].qty, 1)
pr2.cancel()
pi1.cancel()
@@ -963,6 +1011,47 @@ class TestPurchaseReceipt(unittest.TestCase):
self.assertEqual(pr.status, "To Bill")
self.assertAlmostEqual(pr.per_billed, 50.0, places=2)
+ def test_service_item_purchase_with_perpetual_inventory(self):
+ company = '_Test Company with perpetual inventory'
+ service_item = '_Test Non Stock Item'
+
+ before_test_value = frappe.db.get_value('Company', company, 'enable_perpetual_inventory_for_non_stock_items')
+ frappe.db.set_value('Company', company, 'enable_perpetual_inventory_for_non_stock_items', 1)
+ srbnb_account = 'Stock Received But Not Billed - TCP1'
+ frappe.db.set_value('Company', company, 'service_received_but_not_billed', srbnb_account)
+
+ pr = make_purchase_receipt(
+ company=company, item=service_item,
+ warehouse='Finished Goods - TCP1', do_not_save=1
+ )
+ item_row_with_diff_rate = frappe.copy_doc(pr.items[0])
+ item_row_with_diff_rate.rate = 100
+ pr.append('items', item_row_with_diff_rate)
+
+ pr.save()
+ pr.submit()
+
+ item_one_gl_entry = frappe.db.get_all("GL Entry", {
+ 'voucher_type': pr.doctype,
+ 'voucher_no': pr.name,
+ 'account': srbnb_account,
+ 'voucher_detail_no': pr.items[0].name
+ }, pluck="name")
+
+ item_two_gl_entry = frappe.db.get_all("GL Entry", {
+ 'voucher_type': pr.doctype,
+ 'voucher_no': pr.name,
+ 'account': srbnb_account,
+ 'voucher_detail_no': pr.items[1].name
+ }, pluck="name")
+
+ # check if the entries are not merged into one
+ # seperate entries should be made since voucher_detail_no is different
+ self.assertEqual(len(item_one_gl_entry), 1)
+ self.assertEqual(len(item_two_gl_entry), 1)
+
+ frappe.db.set_value('Company', company, 'enable_perpetual_inventory_for_non_stock_items', before_test_value)
+
def get_sl_entries(voucher_type, voucher_no):
return frappe.db.sql(""" select actual_qty, warehouse, stock_value_difference
from `tabStock Ledger Entry` where voucher_type=%s and voucher_no=%s
diff --git a/erpnext/stock/doctype/purchase_receipt_item/purchase_receipt_item.json b/erpnext/stock/doctype/purchase_receipt_item/purchase_receipt_item.json
index efe3642d23c..82cc98e7f75 100644
--- a/erpnext/stock/doctype/purchase_receipt_item/purchase_receipt_item.json
+++ b/erpnext/stock/doctype/purchase_receipt_item/purchase_receipt_item.json
@@ -72,16 +72,18 @@
"warehouse",
"rejected_warehouse",
"from_warehouse",
- "purchase_order",
"material_request",
+ "purchase_order",
+ "purchase_invoice",
"column_break_40",
"is_fixed_asset",
"asset_location",
"asset_category",
"schedule_date",
"quality_inspection",
- "purchase_order_item",
"material_request_item",
+ "purchase_order_item",
+ "purchase_invoice_item",
"purchase_receipt_item",
"delivery_note_item",
"putaway_rule",
@@ -937,7 +939,21 @@
"fieldname": "base_rate_with_margin",
"fieldtype": "Currency",
"label": "Rate With Margin (Company Currency)",
- "options": "Company:company:default_currency",
+ "options": "Company:company:default_currency"
+ },
+ {
+ "fieldname": "purchase_invoice",
+ "fieldtype": "Link",
+ "label": "Purchase Invoice",
+ "options": "Purchase Invoice",
+ "read_only": 1
+ },
+ {
+ "fieldname": "purchase_invoice_item",
+ "fieldtype": "Data",
+ "hidden": 1,
+ "label": "Purchase Invoice Item",
+ "no_copy": 1,
"print_hide": 1,
"read_only": 1
}
@@ -945,7 +961,7 @@
"idx": 1,
"istable": 1,
"links": [],
- "modified": "2021-02-23 00:59:14.360847",
+ "modified": "2021-03-29 04:17:00.336298",
"modified_by": "Administrator",
"module": "Stock",
"name": "Purchase Receipt Item",
diff --git a/erpnext/stock/doctype/putaway_rule/putaway_rule.py b/erpnext/stock/doctype/putaway_rule/putaway_rule.py
index ea26caced04..0f50bcd6ea8 100644
--- a/erpnext/stock/doctype/putaway_rule/putaway_rule.py
+++ b/erpnext/stock/doctype/putaway_rule/putaway_rule.py
@@ -97,7 +97,7 @@ def apply_putaway_rule(doctype, items, company, sync=None, purpose=None):
at_capacity, rules = get_ordered_putaway_rules(item_code, company, source_warehouse=source_warehouse)
if not rules:
- warehouse = source_warehouse or item.warehouse
+ warehouse = source_warehouse or item.get('warehouse')
if at_capacity:
# rules available, but no free space
items_not_accomodated.append([item_code, pending_qty])
diff --git a/erpnext/stock/doctype/quality_inspection/test_quality_inspection.py b/erpnext/stock/doctype/quality_inspection/test_quality_inspection.py
index a7dfc9ee288..f5d076a077a 100644
--- a/erpnext/stock/doctype/quality_inspection/test_quality_inspection.py
+++ b/erpnext/stock/doctype/quality_inspection/test_quality_inspection.py
@@ -1,43 +1,62 @@
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors and Contributors
# See license.txt
-from __future__ import unicode_literals
-import frappe
import unittest
+
+import frappe
from frappe.utils import nowdate
-from erpnext.stock.doctype.item.test_item import create_item
+
+from erpnext.controllers.stock_controller import (
+ QualityInspectionNotSubmittedError,
+ QualityInspectionRejectedError,
+ QualityInspectionRequiredError,
+ make_quality_inspections,
+)
from erpnext.stock.doctype.delivery_note.test_delivery_note import create_delivery_note
-from erpnext.stock.doctype.stock_entry.test_stock_entry import make_stock_entry
-from erpnext.controllers.stock_controller import QualityInspectionRejectedError, QualityInspectionRequiredError, QualityInspectionNotSubmittedError
+from erpnext.stock.doctype.item.test_item import create_item
+from erpnext.stock.doctype.stock_entry.stock_entry_utils import make_stock_entry
# test_records = frappe.get_test_records('Quality Inspection')
+
class TestQualityInspection(unittest.TestCase):
def setUp(self):
create_item("_Test Item with QA")
- frappe.db.set_value("Item", "_Test Item with QA", "inspection_required_before_delivery", 1)
+ frappe.db.set_value(
+ "Item", "_Test Item with QA", "inspection_required_before_delivery", 1
+ )
def test_qa_for_delivery(self):
- make_stock_entry(item_code="_Test Item with QA", target="_Test Warehouse - _TC", qty=1, basic_rate=100)
+ make_stock_entry(
+ item_code="_Test Item with QA",
+ target="_Test Warehouse - _TC",
+ qty=1,
+ basic_rate=100
+ )
dn = create_delivery_note(item_code="_Test Item with QA", do_not_submit=True)
self.assertRaises(QualityInspectionRequiredError, dn.submit)
- qa = create_quality_inspection(reference_type="Delivery Note", reference_name=dn.name, status="Rejected")
+ qa = create_quality_inspection(
+ reference_type="Delivery Note", reference_name=dn.name, status="Rejected"
+ )
dn.reload()
self.assertRaises(QualityInspectionRejectedError, dn.submit)
- frappe.db.set_value("Quality Inspection Reading", {"parent": qa.name}, "status", "Accepted")
+ frappe.db.set_value("Quality Inspection", qa.name, "status", "Accepted")
dn.reload()
dn.submit()
+ qa.reload()
qa.cancel()
dn.reload()
dn.cancel()
def test_qa_not_submit(self):
dn = create_delivery_note(item_code="_Test Item with QA", do_not_submit=True)
- qa = create_quality_inspection(reference_type="Delivery Note", reference_name=dn.name, do_not_submit=True)
+ qa = create_quality_inspection(
+ reference_type="Delivery Note", reference_name=dn.name, do_not_submit=True
+ )
dn.items[0].quality_inspection = qa.name
self.assertRaises(QualityInspectionNotSubmittedError, dn.submit)
@@ -47,21 +66,28 @@ class TestQualityInspection(unittest.TestCase):
def test_value_based_qi_readings(self):
# Test QI based on acceptance values (Non formula)
dn = create_delivery_note(item_code="_Test Item with QA", do_not_submit=True)
- readings = [{
- "specification": "Iron Content", # numeric reading
- "min_value": 0.1,
- "max_value": 0.9,
- "reading_1": "0.4"
- },
- {
- "specification": "Particle Inspection Needed", # non-numeric reading
- "numeric": 0,
- "value": "Yes",
- "reading_value": "Yes"
- }]
+ readings = [
+ {
+ "specification": "Iron Content", # numeric reading
+ "min_value": 0.1,
+ "max_value": 0.9,
+ "reading_1": "0.4"
+ },
+ {
+ "specification": "Particle Inspection Needed", # non-numeric reading
+ "numeric": 0,
+ "value": "Yes",
+ "reading_value": "Yes"
+ }
+ ]
+
+ qa = create_quality_inspection(
+ reference_type="Delivery Note",
+ reference_name=dn.name,
+ readings=readings,
+ do_not_save=True
+ )
- qa = create_quality_inspection(reference_type="Delivery Note", reference_name=dn.name,
- readings=readings, do_not_save=True)
qa.save()
# status must be auto set as per formula
@@ -73,36 +99,43 @@ class TestQualityInspection(unittest.TestCase):
def test_formula_based_qi_readings(self):
dn = create_delivery_note(item_code="_Test Item with QA", do_not_submit=True)
- readings = [{
- "specification": "Iron Content", # numeric reading
- "formula_based_criteria": 1,
- "acceptance_formula": "reading_1 > 0.35 and reading_1 < 0.50",
- "reading_1": "0.4"
- },
- {
- "specification": "Calcium Content", # numeric reading
- "formula_based_criteria": 1,
- "acceptance_formula": "reading_1 > 0.20 and reading_1 < 0.50",
- "reading_1": "0.7"
- },
- {
- "specification": "Mg Content", # numeric reading
- "formula_based_criteria": 1,
- "acceptance_formula": "mean < 0.9",
- "reading_1": "0.5",
- "reading_2": "0.7",
- "reading_3": "random text" # check if random string input causes issues
- },
- {
- "specification": "Calcium Content", # non-numeric reading
- "formula_based_criteria": 1,
- "numeric": 0,
- "acceptance_formula": "reading_value in ('Grade A', 'Grade B', 'Grade C')",
- "reading_value": "Grade B"
- }]
+ readings = [
+ {
+ "specification": "Iron Content", # numeric reading
+ "formula_based_criteria": 1,
+ "acceptance_formula": "reading_1 > 0.35 and reading_1 < 0.50",
+ "reading_1": "0.4"
+ },
+ {
+ "specification": "Calcium Content", # numeric reading
+ "formula_based_criteria": 1,
+ "acceptance_formula": "reading_1 > 0.20 and reading_1 < 0.50",
+ "reading_1": "0.7"
+ },
+ {
+ "specification": "Mg Content", # numeric reading
+ "formula_based_criteria": 1,
+ "acceptance_formula": "mean < 0.9",
+ "reading_1": "0.5",
+ "reading_2": "0.7",
+ "reading_3": "random text" # check if random string input causes issues
+ },
+ {
+ "specification": "Calcium Content", # non-numeric reading
+ "formula_based_criteria": 1,
+ "numeric": 0,
+ "acceptance_formula": "reading_value in ('Grade A', 'Grade B', 'Grade C')",
+ "reading_value": "Grade B"
+ }
+ ]
+
+ qa = create_quality_inspection(
+ reference_type="Delivery Note",
+ reference_name=dn.name,
+ readings=readings,
+ do_not_save=True
+ )
- qa = create_quality_inspection(reference_type="Delivery Note", reference_name=dn.name,
- readings=readings, do_not_save=True)
qa.save()
# status must be auto set as per formula
@@ -114,6 +147,60 @@ class TestQualityInspection(unittest.TestCase):
qa.delete()
dn.delete()
+ def test_make_quality_inspections_from_linked_document(self):
+ dn = create_delivery_note(item_code="_Test Item with QA", do_not_submit=True)
+ for item in dn.items:
+ item.sample_size = item.qty
+ quality_inspections = make_quality_inspections(dn.doctype, dn.name, dn.items)
+ self.assertEqual(len(dn.items), len(quality_inspections))
+
+ # cleanup
+ for qi in quality_inspections:
+ frappe.delete_doc("Quality Inspection", qi)
+ dn.delete()
+
+ def test_rejected_qi_validation(self):
+ """Test if rejected QI blocks Stock Entry as per Stock Settings."""
+ se = make_stock_entry(
+ item_code="_Test Item with QA",
+ target="_Test Warehouse - _TC",
+ qty=1,
+ basic_rate=100,
+ inspection_required=True,
+ do_not_submit=True
+ )
+
+ readings = [
+ {
+ "specification": "Iron Content",
+ "min_value": 0.1,
+ "max_value": 0.9,
+ "reading_1": "0.4"
+ }
+ ]
+
+ qa = create_quality_inspection(
+ reference_type="Stock Entry",
+ reference_name=se.name,
+ readings=readings,
+ status="Rejected"
+ )
+
+ frappe.db.set_value("Stock Settings", None, "action_if_quality_inspection_is_rejected", "Stop")
+ se.reload()
+ self.assertRaises(QualityInspectionRejectedError, se.submit) # when blocked in Stock settings, block rejected QI
+
+ frappe.db.set_value("Stock Settings", None, "action_if_quality_inspection_is_rejected", "Warn")
+ se.reload()
+ se.submit() # when allowed in Stock settings, allow rejected QI
+
+ # teardown
+ qa.reload()
+ qa.cancel()
+ se.reload()
+ se.cancel()
+ frappe.db.set_value("Stock Settings", None, "action_if_quality_inspection_is_rejected", "Stop")
+
def create_quality_inspection(**args):
args = frappe._dict(args)
qa = frappe.new_doc("Quality Inspection")
@@ -129,12 +216,11 @@ def create_quality_inspection(**args):
if not args.readings:
create_quality_inspection_parameter("Size")
readings = {"specification": "Size", "min_value": 0, "max_value": 10}
+ if args.status == "Rejected":
+ readings["reading_1"] = "12" # status is auto set in child on save
else:
readings = args.readings
- if args.status == "Rejected":
- readings["reading_1"] = "12" # status is auto set in child on save
-
if isinstance(readings, list):
for entry in readings:
create_quality_inspection_parameter(entry["specification"])
@@ -149,10 +235,11 @@ def create_quality_inspection(**args):
return qa
+
def create_quality_inspection_parameter(parameter):
if not frappe.db.exists("Quality Inspection Parameter", parameter):
frappe.get_doc({
"doctype": "Quality Inspection Parameter",
"parameter": parameter,
"description": parameter
- }).insert()
\ No newline at end of file
+ }).insert()
diff --git a/erpnext/stock/doctype/repost_item_valuation/repost_item_valuation.py b/erpnext/stock/doctype/repost_item_valuation/repost_item_valuation.py
index f8cfdf83e76..5f31d9caf0d 100644
--- a/erpnext/stock/doctype/repost_item_valuation/repost_item_valuation.py
+++ b/erpnext/stock/doctype/repost_item_valuation/repost_item_valuation.py
@@ -4,8 +4,9 @@
from __future__ import unicode_literals
import frappe, erpnext
+from rq.timeouts import JobTimeoutException
from frappe.model.document import Document
-from frappe.utils import cint, get_link_to_form, add_to_date, today
+from frappe.utils import cint, get_link_to_form, add_to_date, now, today, time_diff_in_hours
from erpnext.stock.stock_ledger import repost_future_sle
from erpnext.accounts.utils import update_gl_entries_after, check_if_stock_and_account_balance_synced
from frappe.utils.user import get_users_with_role
@@ -36,6 +37,9 @@ class RepostItemValuation(Document):
self.db_set('status', status)
def on_submit(self):
+ if not frappe.flags.in_test:
+ return
+
frappe.enqueue(repost, timeout=1800, queue='long',
job_name='repost_sle', now=frappe.flags.in_test, doc=self)
@@ -57,7 +61,8 @@ def repost(doc):
repost_gl_entries(doc)
doc.set_status('Completed')
- except Exception:
+
+ except (Exception, JobTimeoutException):
frappe.db.rollback()
traceback = frappe.get_traceback()
frappe.log_error(traceback)
@@ -124,12 +129,10 @@ def repost_entries():
return
for d in frappe.get_all('Company', filters= {'enable_perpetual_inventory': 1}):
- check_if_stock_and_account_balance_synced(today(), d.company)
+ check_if_stock_and_account_balance_synced(today(), d.name)
def get_repost_item_valuation_entries():
- date = add_to_date(today(), hours=-12)
-
return frappe.db.sql(""" SELECT name from `tabRepost Item Valuation`
- WHERE status != 'Completed' and creation <= %s and docstatus = 1
+ WHERE status in ('Queued', 'In Progress') and creation <= %s and docstatus = 1
ORDER BY timestamp(posting_date, posting_time) asc, creation asc
- """, date, as_dict=1)
\ No newline at end of file
+ """, now(), as_dict=1)
diff --git a/erpnext/stock/doctype/serial_no/serial_no.json b/erpnext/stock/doctype/serial_no/serial_no.json
index 3acf3a9316c..a3d44af4945 100644
--- a/erpnext/stock/doctype/serial_no/serial_no.json
+++ b/erpnext/stock/doctype/serial_no/serial_no.json
@@ -57,7 +57,8 @@
"more_info",
"serial_no_details",
"company",
- "status"
+ "status",
+ "work_order"
],
"fields": [
{
@@ -422,12 +423,18 @@
"label": "Status",
"options": "\nActive\nInactive\nDelivered\nExpired",
"read_only": 1
+ },
+ {
+ "fieldname": "work_order",
+ "fieldtype": "Link",
+ "label": "Work Order",
+ "options": "Work Order"
}
],
"icon": "fa fa-barcode",
"idx": 1,
"links": [],
- "modified": "2020-07-20 20:50:16.660433",
+ "modified": "2021-01-08 14:31:15.375996",
"modified_by": "Administrator",
"module": "Stock",
"name": "Serial No",
diff --git a/erpnext/stock/doctype/serial_no/serial_no.py b/erpnext/stock/doctype/serial_no/serial_no.py
index c8d8ca9e17e..bad7b608acf 100644
--- a/erpnext/stock/doctype/serial_no/serial_no.py
+++ b/erpnext/stock/doctype/serial_no/serial_no.py
@@ -14,6 +14,7 @@ from frappe import _, ValidationError
from erpnext.controllers.stock_controller import StockController
from six import string_types
from six.moves import map
+
class SerialNoCannotCreateDirectError(ValidationError): pass
class SerialNoCannotCannotChangeError(ValidationError): pass
class SerialNoNotRequiredError(ValidationError): pass
@@ -242,7 +243,7 @@ def validate_serial_no(sle, item_det):
if frappe.db.exists("Serial No", serial_no):
sr = frappe.db.get_value("Serial No", serial_no, ["name", "item_code", "batch_no", "sales_order",
"delivery_document_no", "delivery_document_type", "warehouse", "purchase_document_type",
- "purchase_document_no", "company"], as_dict=1)
+ "purchase_document_no", "company", "status"], as_dict=1)
if sr.item_code!=sle.item_code:
if not allow_serial_nos_with_different_item(serial_no, sle):
@@ -265,6 +266,9 @@ def validate_serial_no(sle, item_det):
frappe.throw(_("Serial No {0} does not belong to Warehouse {1}").format(serial_no,
sle.warehouse), SerialNoWarehouseError)
+ if not sr.purchase_document_no:
+ frappe.throw(_("Serial No {0} not in stock").format(serial_no), SerialNoNotExistsError)
+
if sle.voucher_type in ("Delivery Note", "Sales Invoice"):
if sr.batch_no and sr.batch_no != sle.batch_no:
@@ -322,11 +326,35 @@ def validate_serial_no(sle, item_det):
frappe.throw(_("Serial Nos Required for Serialized Item {0}").format(sle.item_code),
SerialNoRequiredError)
elif serial_nos:
+ # SLE is being cancelled and has serial nos
for serial_no in serial_nos:
- sr = frappe.db.get_value("Serial No", serial_no, ["name", "warehouse"], as_dict=1)
- if sr and cint(sle.actual_qty) < 0 and sr.warehouse != sle.warehouse:
- frappe.throw(_("Cannot cancel {0} {1} because Serial No {2} does not belong to the warehouse {3}")
- .format(sle.voucher_type, sle.voucher_no, serial_no, sle.warehouse))
+ check_serial_no_validity_on_cancel(serial_no, sle)
+
+def check_serial_no_validity_on_cancel(serial_no, sle):
+ sr = frappe.db.get_value("Serial No", serial_no, ["name", "warehouse", "company", "status"], as_dict=1)
+ sr_link = frappe.utils.get_link_to_form("Serial No", serial_no)
+ doc_link = frappe.utils.get_link_to_form(sle.voucher_type, sle.voucher_no)
+ actual_qty = cint(sle.actual_qty)
+ is_stock_reco = sle.voucher_type == "Stock Reconciliation"
+ msg = None
+
+ if sr and (actual_qty < 0 or is_stock_reco) and sr.warehouse != sle.warehouse:
+ # receipt(inward) is being cancelled
+ msg = _("Cannot cancel {0} {1} as Serial No {2} does not belong to the warehouse {3}").format(
+ sle.voucher_type, doc_link, sr_link, frappe.bold(sle.warehouse))
+ elif sr and actual_qty > 0 and not is_stock_reco:
+ # delivery is being cancelled, check for warehouse.
+ if sr.warehouse:
+ # serial no is active in another warehouse/company.
+ msg = _("Cannot cancel {0} {1} as Serial No {2} is active in warehouse {3}").format(
+ sle.voucher_type, doc_link, sr_link, frappe.bold(sr.warehouse))
+ elif sr.company != sle.company and sr.status == "Delivered":
+ # serial no is inactive (allowed) or delivered from another company (block).
+ msg = _("Cannot cancel {0} {1} as Serial No {2} does not belong to the company {3}").format(
+ sle.voucher_type, doc_link, sr_link, frappe.bold(sle.company))
+
+ if msg:
+ frappe.throw(msg, title=_("Cannot cancel"))
def validate_material_transfer_entry(sle_doc):
sle_doc.update({
@@ -357,19 +385,6 @@ def has_serial_no_exists(sn, sle):
if sn.company != sle.company:
return False
- status = False
- if sn.purchase_document_no:
- if (sle.voucher_type in ['Purchase Receipt', 'Stock Entry', "Purchase Invoice"] and
- sn.delivery_document_type not in ['Purchase Receipt', 'Stock Entry', "Purchase Invoice"]):
- status = True
-
- # If status is receipt then system will allow to in-ward the delivered serial no
- if (status and sle.voucher_type == "Stock Entry" and frappe.db.get_value("Stock Entry",
- sle.voucher_no, "purpose") in ("Material Receipt", "Material Transfer")):
- status = False
-
- return status
-
def allow_serial_nos_with_different_item(sle_serial_no, sle):
"""
Allows same serial nos for raw materials and finished goods
@@ -458,16 +473,13 @@ def get_serial_nos(serial_no):
if s.strip()]
def update_args_for_serial_no(serial_no_doc, serial_no, args, is_new=False):
- serial_no_doc.update({
- "item_code": args.get("item_code"),
- "company": args.get("company"),
- "batch_no": args.get("batch_no"),
- "via_stock_ledger": args.get("via_stock_ledger") or True,
- "supplier": args.get("supplier"),
- "location": args.get("location"),
- "warehouse": (args.get("warehouse")
- if args.get("actual_qty", 0) > 0 else None)
- })
+ for field in ["item_code", "work_order", "company", "batch_no", "supplier", "location"]:
+ if args.get(field):
+ serial_no_doc.set(field, args.get(field))
+
+ serial_no_doc.via_stock_ledger = args.get("via_stock_ledger") or True
+ serial_no_doc.warehouse = (args.get("warehouse")
+ if args.get("actual_qty", 0) > 0 else None)
if is_new:
serial_no_doc.serial_no = serial_no
@@ -598,7 +610,7 @@ def fetch_serial_numbers(filters, qty, do_not_include=[]):
batch_nos = filters.get("batch_no")
expiry_date = filters.get("expiry_date")
if batch_nos:
- batch_no_condition = """and sr.batch_no in ({}) """.format(', '.join(["'%s'" % d for d in batch_nos]))
+ batch_no_condition = """and sr.batch_no in ({}) """.format(', '.join("'%s'" % d for d in batch_nos))
if expiry_date:
batch_join_selection = "LEFT JOIN `tabBatch` batch on sr.batch_no = batch.name "
diff --git a/erpnext/stock/doctype/serial_no/test_serial_no.py b/erpnext/stock/doctype/serial_no/test_serial_no.py
index ed70790b2ca..cde7fe07c63 100644
--- a/erpnext/stock/doctype/serial_no/test_serial_no.py
+++ b/erpnext/stock/doctype/serial_no/test_serial_no.py
@@ -40,16 +40,139 @@ class TestSerialNo(unittest.TestCase):
se = make_serialized_item(target_warehouse="_Test Warehouse - _TC")
serial_nos = get_serial_nos(se.get("items")[0].serial_no)
- create_delivery_note(item_code="_Test Serialized Item With Series", qty=1, serial_no=serial_nos[0])
+ dn = create_delivery_note(item_code="_Test Serialized Item With Series", qty=1, serial_no=serial_nos[0])
+
+ serial_no = frappe.get_doc("Serial No", serial_nos[0])
+
+ # check Serial No details after delivery
+ self.assertEqual(serial_no.status, "Delivered")
+ self.assertEqual(serial_no.warehouse, None)
+ self.assertEqual(serial_no.company, "_Test Company")
+ self.assertEqual(serial_no.delivery_document_type, "Delivery Note")
+ self.assertEqual(serial_no.delivery_document_no, dn.name)
wh = create_warehouse("_Test Warehouse", company="_Test Company 1")
- make_purchase_receipt(item_code="_Test Serialized Item With Series", qty=1, serial_no=serial_nos[0],
+ pr = make_purchase_receipt(item_code="_Test Serialized Item With Series", qty=1, serial_no=serial_nos[0],
company="_Test Company 1", warehouse=wh)
- serial_no = frappe.db.get_value("Serial No", serial_nos[0], ["warehouse", "company"], as_dict=1)
+ serial_no.reload()
+ # check Serial No details after purchase in second company
+ self.assertEqual(serial_no.status, "Active")
self.assertEqual(serial_no.warehouse, wh)
self.assertEqual(serial_no.company, "_Test Company 1")
+ self.assertEqual(serial_no.purchase_document_type, "Purchase Receipt")
+ self.assertEqual(serial_no.purchase_document_no, pr.name)
+
+ def test_inter_company_transfer_intermediate_cancellation(self):
+ """
+ Receive into and Deliver Serial No from one company.
+ Then Receive into and Deliver from second company.
+ Try to cancel intermediate receipts/deliveries to test if it is blocked.
+ """
+ se = make_serialized_item(target_warehouse="_Test Warehouse - _TC")
+ serial_nos = get_serial_nos(se.get("items")[0].serial_no)
+
+ sn_doc = frappe.get_doc("Serial No", serial_nos[0])
+
+ # check Serial No details after purchase in first company
+ self.assertEqual(sn_doc.status, "Active")
+ self.assertEqual(sn_doc.company, "_Test Company")
+ self.assertEqual(sn_doc.warehouse, "_Test Warehouse - _TC")
+ self.assertEqual(sn_doc.purchase_document_no, se.name)
+
+ dn = create_delivery_note(item_code="_Test Serialized Item With Series",
+ qty=1, serial_no=serial_nos[0])
+ sn_doc.reload()
+ # check Serial No details after delivery from **first** company
+ self.assertEqual(sn_doc.status, "Delivered")
+ self.assertEqual(sn_doc.company, "_Test Company")
+ self.assertEqual(sn_doc.warehouse, None)
+ self.assertEqual(sn_doc.delivery_document_no, dn.name)
+
+ # try cancelling the first Serial No Receipt, even though it is delivered
+ # block cancellation is Serial No is out of the warehouse
+ self.assertRaises(frappe.ValidationError, se.cancel)
+
+ # receive serial no in second company
+ wh = create_warehouse("_Test Warehouse", company="_Test Company 1")
+ pr = make_purchase_receipt(item_code="_Test Serialized Item With Series",
+ qty=1, serial_no=serial_nos[0], company="_Test Company 1", warehouse=wh)
+ sn_doc.reload()
+
+ self.assertEqual(sn_doc.warehouse, wh)
+ # try cancelling the delivery from the first company
+ # block cancellation as Serial No belongs to different company
+ self.assertRaises(frappe.ValidationError, dn.cancel)
+
+ # deliver from second company
+ dn_2 = create_delivery_note(item_code="_Test Serialized Item With Series",
+ qty=1, serial_no=serial_nos[0], company="_Test Company 1", warehouse=wh)
+ sn_doc.reload()
+
+ # check Serial No details after delivery from **second** company
+ self.assertEqual(sn_doc.status, "Delivered")
+ self.assertEqual(sn_doc.company, "_Test Company 1")
+ self.assertEqual(sn_doc.warehouse, None)
+ self.assertEqual(sn_doc.delivery_document_no, dn_2.name)
+
+ # cannot cancel any intermediate document before last Delivery Note
+ self.assertRaises(frappe.ValidationError, se.cancel)
+ self.assertRaises(frappe.ValidationError, dn.cancel)
+ self.assertRaises(frappe.ValidationError, pr.cancel)
+
+ def test_inter_company_transfer_fallback_on_cancel(self):
+ """
+ Test Serial No state changes on cancellation.
+ If Delivery cancelled, it should fall back on last Receipt in the same company.
+ If Receipt is cancelled, it should be Inactive in the same company.
+ """
+ # Receipt in **first** company
+ se = make_serialized_item(target_warehouse="_Test Warehouse - _TC")
+ serial_nos = get_serial_nos(se.get("items")[0].serial_no)
+ sn_doc = frappe.get_doc("Serial No", serial_nos[0])
+
+ # Delivery from first company
+ dn = create_delivery_note(item_code="_Test Serialized Item With Series",
+ qty=1, serial_no=serial_nos[0])
+
+ # Receipt in **second** company
+ wh = create_warehouse("_Test Warehouse", company="_Test Company 1")
+ pr = make_purchase_receipt(item_code="_Test Serialized Item With Series",
+ qty=1, serial_no=serial_nos[0], company="_Test Company 1", warehouse=wh)
+
+ # Delivery from second company
+ dn_2 = create_delivery_note(item_code="_Test Serialized Item With Series",
+ qty=1, serial_no=serial_nos[0], company="_Test Company 1", warehouse=wh)
+ sn_doc.reload()
+
+ self.assertEqual(sn_doc.status, "Delivered")
+ self.assertEqual(sn_doc.company, "_Test Company 1")
+ self.assertEqual(sn_doc.delivery_document_no, dn_2.name)
+
+ dn_2.cancel()
+ sn_doc.reload()
+ # Fallback on Purchase Receipt if Delivery is cancelled
+ self.assertEqual(sn_doc.status, "Active")
+ self.assertEqual(sn_doc.company, "_Test Company 1")
+ self.assertEqual(sn_doc.warehouse, wh)
+ self.assertEqual(sn_doc.purchase_document_no, pr.name)
+
+ pr.cancel()
+ sn_doc.reload()
+ # Inactive in same company if Receipt cancelled
+ self.assertEqual(sn_doc.status, "Inactive")
+ self.assertEqual(sn_doc.company, "_Test Company 1")
+ self.assertEqual(sn_doc.warehouse, None)
+
+ dn.cancel()
+ sn_doc.reload()
+ # Fallback on Purchase Receipt in FIRST company if
+ # Delivery from FIRST company is cancelled
+ self.assertEqual(sn_doc.status, "Active")
+ self.assertEqual(sn_doc.company, "_Test Company")
+ self.assertEqual(sn_doc.warehouse, "_Test Warehouse - _TC")
+ self.assertEqual(sn_doc.purchase_document_no, se.name)
def tearDown(self):
frappe.db.rollback()
\ No newline at end of file
diff --git a/erpnext/stock/doctype/shipment/shipment.js b/erpnext/stock/doctype/shipment/shipment.js
index 7af16af8986..ce2906ecbe9 100644
--- a/erpnext/stock/doctype/shipment/shipment.js
+++ b/erpnext/stock/doctype/shipment/shipment.js
@@ -363,43 +363,6 @@ frappe.ui.form.on('Shipment', {
if (frm.doc.pickup_date < frappe.datetime.get_today()) {
frappe.throw(__("Pickup Date cannot be before this day"));
}
- if (frm.doc.pickup_date == frappe.datetime.get_today()) {
- var pickup_time = frm.events.get_pickup_time(frm);
- frm.set_value("pickup_from", pickup_time);
- frm.trigger('set_pickup_to_time');
- }
- },
- pickup_from: function(frm) {
- var pickup_time = frm.events.get_pickup_time(frm);
- if (frm.doc.pickup_from && frm.doc.pickup_date == frappe.datetime.get_today()) {
- let current_hour = pickup_time.split(':')[0];
- let current_min = pickup_time.split(':')[1];
- let pickup_hour = frm.doc.pickup_from.split(':')[0];
- let pickup_min = frm.doc.pickup_from.split(':')[1];
- if (pickup_hour < current_hour || (pickup_hour == current_hour && pickup_min < current_min)) {
- frm.set_value("pickup_from", pickup_time);
- frappe.throw(__("Pickup Time cannot be in the past"));
- }
- }
- frm.trigger('set_pickup_to_time');
- },
- get_pickup_time: function() {
- let current_hour = new Date().getHours();
- let current_min = new Date().toLocaleString('en-US', {minute: 'numeric'});
- if (current_min < 30) {
- current_min = '30';
- } else {
- current_min = '00';
- current_hour = Number(current_hour)+1;
- }
- let pickup_time = current_hour +':'+ current_min;
- return pickup_time;
- },
- set_pickup_to_time: function(frm) {
- let pickup_to_hour = Number(frm.doc.pickup_from.split(':')[0])+5;
- let pickup_to_min = frm.doc.pickup_from.split(':')[1];
- let pickup_to = pickup_to_hour +':'+ pickup_to_min;
- frm.set_value("pickup_to", pickup_to);
},
clear_pickup_fields: function(frm) {
let fields = ["pickup_address_name", "pickup_contact_name", "pickup_address", "pickup_contact", "pickup_contact_email", "pickup_contact_person"];
diff --git a/erpnext/stock/doctype/shipment/shipment.json b/erpnext/stock/doctype/shipment/shipment.json
index 76c331c5c25..a33cbc288c5 100644
--- a/erpnext/stock/doctype/shipment/shipment.json
+++ b/erpnext/stock/doctype/shipment/shipment.json
@@ -275,14 +275,16 @@
"default": "09:00",
"fieldname": "pickup_from",
"fieldtype": "Time",
- "label": "Pickup from"
+ "label": "Pickup from",
+ "reqd": 1
},
{
"allow_on_submit": 1,
"default": "17:00",
"fieldname": "pickup_to",
"fieldtype": "Time",
- "label": "Pickup to"
+ "label": "Pickup to",
+ "reqd": 1
},
{
"fieldname": "column_break_36",
@@ -431,7 +433,7 @@
],
"is_submittable": 1,
"links": [],
- "modified": "2020-12-25 15:02:34.891976",
+ "modified": "2021-04-13 17:14:18.181818",
"modified_by": "Administrator",
"module": "Stock",
"name": "Shipment",
@@ -469,4 +471,4 @@
"sort_field": "modified",
"sort_order": "DESC",
"track_changes": 1
-}
\ No newline at end of file
+}
diff --git a/erpnext/stock/doctype/shipment/shipment.py b/erpnext/stock/doctype/shipment/shipment.py
index 4697a7b3235..01fcee4cac2 100644
--- a/erpnext/stock/doctype/shipment/shipment.py
+++ b/erpnext/stock/doctype/shipment/shipment.py
@@ -23,10 +23,10 @@ class Shipment(Document):
frappe.throw(_('Please enter Shipment Parcel information'))
if self.value_of_goods == 0:
frappe.throw(_('Value of goods cannot be 0'))
- self.status = 'Submitted'
+ self.db_set('status', 'Submitted')
def on_cancel(self):
- self.status = 'Cancelled'
+ self.db_set('status', 'Cancelled')
def validate_weight(self):
for parcel in self.shipment_parcel:
diff --git a/erpnext/stock/doctype/stock_entry/stock_entry.js b/erpnext/stock/doctype/stock_entry/stock_entry.js
index 98246fb0240..67083930272 100644
--- a/erpnext/stock/doctype/stock_entry/stock_entry.js
+++ b/erpnext/stock/doctype/stock_entry/stock_entry.js
@@ -107,6 +107,7 @@ frappe.ui.form.on('Stock Entry', {
frappe.flags.hide_serial_batch_dialog = true;
}
});
+ attach_bom_items(frm.doc.bom_no);
},
setup_quality_inspection: function(frm) {
@@ -114,6 +115,14 @@ frappe.ui.form.on('Stock Entry', {
return;
}
+ if (!frm.is_new() && frm.doc.docstatus === 0) {
+ frm.add_custom_button(__("Quality Inspection(s)"), () => {
+ let transaction_controller = new erpnext.TransactionController({ frm: frm });
+ transaction_controller.make_quality_inspection();
+ }, __("Create"));
+ frm.page.set_inner_btn_group_as_primary(__('Create'));
+ }
+
let quality_inspection_field = frm.get_docfield("items", "quality_inspection");
quality_inspection_field.get_route_options_for_new_doc = function(row) {
if (frm.is_new()) return;
@@ -154,7 +163,7 @@ frappe.ui.form.on('Stock Entry', {
refresh: function(frm) {
if(!frm.doc.docstatus) {
frm.trigger('validate_purpose_consumption');
- frm.add_custom_button(__('Create Material Request'), function() {
+ frm.add_custom_button(__('Material Request'), function() {
frappe.model.with_doctype('Material Request', function() {
var mr = frappe.model.get_new_doc('Material Request');
var items = frm.get_field('items').grid.get_selected_children();
@@ -177,7 +186,7 @@ frappe.ui.form.on('Stock Entry', {
});
frappe.set_route('Form', 'Material Request', mr.name);
});
- });
+ }, __("Create"));
}
if(frm.doc.items) {
@@ -311,6 +320,7 @@ frappe.ui.form.on('Stock Entry', {
}
frm.trigger("setup_quality_inspection");
+ attach_bom_items(frm.doc.bom_no)
},
stock_entry_type: function(frm){
@@ -558,7 +568,6 @@ frappe.ui.form.on('Stock Entry', {
})
);
}
-
for (let i in frm.doc.items) {
let item = frm.doc.items[i];
@@ -599,7 +608,6 @@ frappe.ui.form.on('Stock Entry', {
add_to_transit: function(frm) {
if(frm.doc.add_to_transit && frm.doc.purpose=='Material Transfer') {
frm.set_value('to_warehouse', '');
- frm.set_value('stock_entry_type', 'Material Transfer');
frm.fields_dict.to_warehouse.get_query = function() {
return {
filters:{
@@ -609,12 +617,13 @@ frappe.ui.form.on('Stock Entry', {
}
};
};
- frm.trigger('set_tansit_warehouse');
+ frm.trigger('set_transit_warehouse');
}
},
- set_tansit_warehouse: function(frm) {
- if(frm.doc.add_to_transit && frm.doc.purpose == 'Material Transfer' && !frm.doc.to_warehouse) {
+ set_transit_warehouse: function(frm) {
+ if(frm.doc.add_to_transit && frm.doc.purpose == 'Material Transfer' && !frm.doc.to_warehouse
+ && frm.doc.from_warehouse) {
let dt = frm.doc.from_warehouse ? 'Warehouse' : 'Company';
let dn = frm.doc.from_warehouse ? frm.doc.from_warehouse : frm.doc.company;
frappe.db.get_value(dt, dn, 'default_in_transit_warehouse', (r) => {
@@ -856,7 +865,6 @@ erpnext.stock.StockEntry = erpnext.stock.StockController.extend({
}
erpnext.hide_company();
erpnext.utils.add_item(this.frm);
- this.frm.trigger('add_to_transit');
},
scan_barcode: function() {
@@ -921,6 +929,7 @@ erpnext.stock.StockEntry = erpnext.stock.StockController.extend({
method: "get_items",
callback: function(r) {
if(!r.exc) refresh_field("items");
+ if(me.frm.doc.bom_no) attach_bom_items(me.frm.doc.bom_no)
}
});
}
@@ -977,14 +986,17 @@ erpnext.stock.StockEntry = erpnext.stock.StockController.extend({
items_add: function(doc, cdt, cdn) {
var row = frappe.get_doc(cdt, cdn);
- this.frm.script_manager.copy_from_first_row("items", row, ["expense_account", "cost_center"]);
+
+ if (!(row.expense_account && row.cost_center)) {
+ this.frm.script_manager.copy_from_first_row("items", row, ["expense_account", "cost_center"]);
+ }
if(!row.s_warehouse) row.s_warehouse = this.frm.doc.from_warehouse;
if(!row.t_warehouse) row.t_warehouse = this.frm.doc.to_warehouse;
},
from_warehouse: function(doc) {
- this.frm.trigger('set_tansit_warehouse');
+ this.frm.trigger('set_transit_warehouse');
this.set_warehouse_in_children(doc.items, "s_warehouse", doc.from_warehouse);
},
@@ -998,7 +1010,7 @@ erpnext.stock.StockEntry = erpnext.stock.StockController.extend({
},
items_on_form_rendered: function(doc, grid_row) {
- erpnext.setup_serial_no();
+ erpnext.setup_serial_or_batch_no();
},
toggle_related_fields: function(doc) {
@@ -1066,4 +1078,26 @@ erpnext.stock.select_batch_and_serial_no = (frm, item) => {
}
+function attach_bom_items(bom_no) {
+ if (!bom_no) {
+ return
+ }
+
+ if (check_should_not_attach_bom_items(bom_no)) return
+ frappe.db.get_doc("BOM",bom_no).then(bom => {
+ const {name, items} = bom
+ erpnext.stock.bom = {name, items:{}}
+ items.forEach(item => {
+ erpnext.stock.bom.items[item.item_code] = item;
+ });
+ });
+}
+
+function check_should_not_attach_bom_items(bom_no) {
+ return (
+ bom_no === undefined ||
+ (erpnext.stock.bom && erpnext.stock.bom.name === bom_no)
+ );
+}
+
$.extend(cur_frm.cscript, new erpnext.stock.StockEntry({frm: cur_frm}));
diff --git a/erpnext/stock/doctype/stock_entry/stock_entry.json b/erpnext/stock/doctype/stock_entry/stock_entry.json
index 98c047a09ed..523d332b8f4 100644
--- a/erpnext/stock/doctype/stock_entry/stock_entry.json
+++ b/erpnext/stock/doctype/stock_entry/stock_entry.json
@@ -59,10 +59,6 @@
"supplier_name",
"supplier_address",
"address_display",
- "column_break_39",
- "customer",
- "customer_name",
- "customer_address",
"accounting_dimensions_section",
"project",
"dimension_col_break",
@@ -78,7 +74,8 @@
"total_amount",
"job_card",
"amended_from",
- "credit_note"
+ "credit_note",
+ "is_return"
],
"fields": [
{
@@ -435,13 +432,13 @@
},
{
"collapsible": 1,
- "depends_on": "eval: in_list([\"Sales Return\", \"Purchase Return\", \"Send to Subcontractor\"], doc.purpose)",
+ "depends_on": "eval:doc.purpose === \"Send to Subcontractor\"",
"fieldname": "contact_section",
"fieldtype": "Section Break",
- "label": "Customer or Supplier Details"
+ "label": "Supplier Details"
},
{
- "depends_on": "eval:doc.purpose==\"Purchase Return\" || doc.purpose==\"Send to Subcontractor\"",
+ "depends_on": "eval:doc.purpose === \"Send to Subcontractor\"",
"fieldname": "supplier",
"fieldtype": "Link",
"label": "Supplier",
@@ -453,7 +450,7 @@
},
{
"bold": 1,
- "depends_on": "eval:doc.purpose==\"Purchase Return\" || doc.purpose==\"Send to Subcontractor\"",
+ "depends_on": "eval:doc.purpose === \"Send to Subcontractor\"",
"fieldname": "supplier_name",
"fieldtype": "Data",
"label": "Supplier Name",
@@ -463,7 +460,7 @@
"read_only": 1
},
{
- "depends_on": "eval:doc.purpose==\"Purchase Return\" || doc.purpose==\"Send to Subcontractor\"",
+ "depends_on": "eval:doc.purpose === \"Send to Subcontractor\"",
"fieldname": "supplier_address",
"fieldtype": "Link",
"label": "Supplier Address",
@@ -477,41 +474,6 @@
"fieldtype": "Small Text",
"label": "Address"
},
- {
- "fieldname": "column_break_39",
- "fieldtype": "Column Break"
- },
- {
- "depends_on": "eval:doc.purpose==\"Sales Return\"",
- "fieldname": "customer",
- "fieldtype": "Link",
- "label": "Customer",
- "no_copy": 1,
- "oldfieldname": "customer",
- "oldfieldtype": "Link",
- "options": "Customer",
- "print_hide": 1
- },
- {
- "bold": 1,
- "depends_on": "eval:doc.purpose==\"Sales Return\"",
- "fieldname": "customer_name",
- "fieldtype": "Data",
- "label": "Customer Name",
- "no_copy": 1,
- "oldfieldname": "customer_name",
- "oldfieldtype": "Data",
- "read_only": 1
- },
- {
- "depends_on": "eval:doc.purpose==\"Sales Return\"",
- "fieldname": "customer_address",
- "fieldtype": "Small Text",
- "label": "Customer Address",
- "no_copy": 1,
- "oldfieldname": "customer_address",
- "oldfieldtype": "Small Text"
- },
{
"collapsible": 1,
"fieldname": "printing_settings",
@@ -637,6 +599,8 @@
{
"default": "0",
"depends_on": "eval: doc.purpose=='Material Transfer' && !doc.outgoing_stock_entry",
+ "fetch_from": "stock_entry_type.add_to_transit",
+ "fetch_if_empty": 1,
"fieldname": "add_to_transit",
"fieldtype": "Check",
"label": "Add to Transit",
@@ -648,6 +612,16 @@
"fieldname": "apply_putaway_rule",
"fieldtype": "Check",
"label": "Apply Putaway Rule"
+ },
+ {
+ "default": "0",
+ "fieldname": "is_return",
+ "fieldtype": "Check",
+ "hidden": 1,
+ "label": "Is Return",
+ "no_copy": 1,
+ "print_hide": 1,
+ "read_only": 1
}
],
"icon": "fa fa-file-text",
@@ -655,7 +629,7 @@
"index_web_pages_for_search": 1,
"is_submittable": 1,
"links": [],
- "modified": "2020-12-09 14:58:13.267321",
+ "modified": "2021-05-26 17:07:58.015737",
"modified_by": "Administrator",
"module": "Stock",
"name": "Stock Entry",
diff --git a/erpnext/stock/doctype/stock_entry/stock_entry.py b/erpnext/stock/doctype/stock_entry/stock_entry.py
index f8ac400a8e9..654755ec2fb 100644
--- a/erpnext/stock/doctype/stock_entry/stock_entry.py
+++ b/erpnext/stock/doctype/stock_entry/stock_entry.py
@@ -76,6 +76,7 @@ class StockEntry(StockController):
self.validate_difference_account()
self.set_job_card_data()
self.set_purpose_for_stock_entry()
+ self.validate_duplicate_serial_no()
if not self.from_bom:
self.fg_completed_qty = 0.0
@@ -96,8 +97,7 @@ class StockEntry(StockController):
update_serial_nos_after_submit(self, "items")
self.update_work_order()
self.validate_purchase_order()
- if self.purchase_order and self.purpose == "Send to Subcontractor":
- self.update_purchase_order_supplied_items()
+ self.update_purchase_order_supplied_items()
self.make_gl_entries()
@@ -116,9 +116,7 @@ class StockEntry(StockController):
self.set_material_request_transfer_status('Completed')
def on_cancel(self):
-
- if self.purchase_order and self.purpose == "Send to Subcontractor":
- self.update_purchase_order_supplied_items()
+ self.update_purchase_order_supplied_items()
if self.work_order and self.purpose == "Material Consumption for Manufacture":
self.validate_work_order_status()
@@ -398,8 +396,12 @@ class StockEntry(StockController):
and item_code = %s
and ifnull(s_warehouse,'')='' """ % (", ".join(["%s" * len(other_ste)]), "%s"), args)[0][0]
if fg_qty_already_entered and fg_qty_already_entered >= qty:
- frappe.throw(_("Stock Entries already created for Work Order ")
- + self.work_order + ":" + ", ".join(other_ste), DuplicateEntryForWorkOrderError)
+ frappe.throw(
+ _("Stock Entries already created for Work Order {0}: {1}").format(
+ self.work_order, ", ".join(other_ste)
+ ),
+ DuplicateEntryForWorkOrderError,
+ )
def set_actual_qty(self):
allow_negative_stock = cint(frappe.db.get_value("Stock Settings", None, "allow_negative_stock"))
@@ -435,6 +437,7 @@ class StockEntry(StockController):
if transferred_serial_no:
d.serial_no = transferred_serial_no
+ @frappe.whitelist()
def get_stock_and_rate(self):
"""
Updates rate and availability of all the items.
@@ -459,7 +462,7 @@ class StockEntry(StockController):
"""
# Set rate for outgoing items
outgoing_items_cost = self.set_rate_for_outgoing_items(reset_outgoing_rate, raise_error_if_no_rate)
- finished_item_qty = sum([d.transfer_qty for d in self.items if d.is_finished_item])
+ finished_item_qty = sum(d.transfer_qty for d in self.items if d.is_finished_item)
# Set basic rate for incoming items
for d in self.get('items'):
@@ -495,6 +498,7 @@ class StockEntry(StockController):
d.basic_amount = flt(flt(d.transfer_qty) * flt(d.basic_rate), d.precision("basic_amount"))
if not d.t_warehouse:
outgoing_items_cost += flt(d.basic_amount)
+
return outgoing_items_cost
def get_args_for_incoming_rate(self, item):
@@ -525,7 +529,7 @@ class StockEntry(StockController):
scrap_items_cost = sum([flt(d.basic_amount) for d in self.get("items") if d.is_scrap_item])
# Get raw materials cost from BOM if multiple material consumption entries
- if frappe.db.get_single_value("Manufacturing Settings", "material_consumption"):
+ if frappe.db.get_single_value("Manufacturing Settings", "material_consumption", cache=True):
bom_items = self.get_bom_raw_materials(finished_item_qty)
outgoing_items_cost = sum([flt(row.qty)*flt(row.rate) for row in bom_items.values()])
@@ -582,6 +586,22 @@ class StockEntry(StockController):
self.purpose = frappe.get_cached_value('Stock Entry Type',
self.stock_entry_type, 'purpose')
+ def validate_duplicate_serial_no(self):
+ warehouse_wise_serial_nos = {}
+
+ # In case of repack the source and target serial nos could be same
+ for warehouse in ['s_warehouse', 't_warehouse']:
+ serial_nos = []
+ for row in self.items:
+ if not (row.serial_no and row.get(warehouse)): continue
+
+ for sn in get_serial_nos(row.serial_no):
+ if sn in serial_nos:
+ frappe.throw(_('The serial no {0} has added multiple times in the stock entry {1}')
+ .format(frappe.bold(sn), self.name))
+
+ serial_nos.append(sn)
+
def validate_purchase_order(self):
"""Throw exception if more raw material is transferred against Purchase Order than in
the raw materials supplied table"""
@@ -699,6 +719,10 @@ class StockEntry(StockController):
frappe.throw(_("Multiple items cannot be marked as finished item"))
if self.purpose == "Manufacture":
+ if not finished_items:
+ frappe.throw(_('Finished Good has not set in the stock entry {0}')
+ .format(self.name))
+
allowance_percentage = flt(frappe.db.get_single_value("Manufacturing Settings",
"overproduction_percentage_for_work_order"))
@@ -835,6 +859,7 @@ class StockEntry(StockController):
pro_doc.run_method("update_work_order_qty")
if self.purpose == "Manufacture":
pro_doc.run_method("update_planned_qty")
+ pro_doc.update_batch_produced_qty(self)
if not pro_doc.operations:
pro_doc.set_actual_dates()
@@ -986,10 +1011,12 @@ class StockEntry(StockController):
if self.purchase_order and self.purpose == "Send to Subcontractor":
#Get PO Supplied Items Details
item_wh = frappe._dict(frappe.db.sql("""
- select rm_item_code, reserve_warehouse
- from `tabPurchase Order` po, `tabPurchase Order Item Supplied` poitemsup
- where po.name = poitemsup.parent
- and po.name = %s""",self.purchase_order))
+ SELECT
+ rm_item_code, reserve_warehouse
+ FROM
+ `tabPurchase Order` po, `tabPurchase Order Item Supplied` poitemsup
+ WHERE
+ po.name = poitemsup.parent and po.name = %s """,self.purchase_order))
for item in itervalues(item_dict):
if self.pro_doc and cint(self.pro_doc.from_wip_warehouse):
@@ -1055,18 +1082,64 @@ class StockEntry(StockController):
# in case of BOM
to_warehouse = item.get("default_warehouse")
+ args = {
+ "to_warehouse": to_warehouse,
+ "from_warehouse": "",
+ "qty": self.fg_completed_qty,
+ "item_name": item.item_name,
+ "description": item.description,
+ "stock_uom": item.stock_uom,
+ "expense_account": item.get("expense_account"),
+ "cost_center": item.get("buying_cost_center"),
+ "is_finished_item": 1
+ }
+
+ if self.work_order and self.pro_doc.has_batch_no and cint(frappe.db.get_single_value('Manufacturing Settings',
+ 'make_serial_no_batch_from_work_order', cache=True)):
+ self.set_batchwise_finished_goods(args, item)
+ else:
+ self.add_finished_goods(args, item)
+
+ def set_batchwise_finished_goods(self, args, item):
+ filters = {
+ "reference_name": self.pro_doc.name,
+ "reference_doctype": self.pro_doc.doctype,
+ "qty_to_produce": (">", 0)
+ }
+
+ fields = ["qty_to_produce as qty", "produced_qty", "name"]
+
+ data = frappe.get_all("Batch", filters = filters, fields = fields, order_by="creation asc")
+
+ if not data:
+ self.add_finished_goods(args, item)
+ else:
+ self.add_batchwise_finished_good(data, args, item)
+
+ def add_batchwise_finished_good(self, data, args, item):
+ qty = flt(self.fg_completed_qty)
+
+ for row in data:
+ batch_qty = flt(row.qty) - flt(row.produced_qty)
+ if not batch_qty:
+ continue
+
+ if qty <=0:
+ break
+
+ fg_qty = batch_qty
+ if batch_qty >= qty:
+ fg_qty = qty
+
+ qty -= batch_qty
+ args["qty"] = fg_qty
+ args["batch_no"] = row.name
+
+ self.add_finished_goods(args, item)
+
+ def add_finished_goods(self, args, item):
self.add_to_stock_entry_detail({
- item.name: {
- "to_warehouse": to_warehouse,
- "from_warehouse": "",
- "qty": self.fg_completed_qty,
- "item_name": item.item_name,
- "description": item.description,
- "stock_uom": item.stock_uom,
- "expense_account": item.get("expense_account"),
- "cost_center": item.get("buying_cost_center"),
- "is_finished_item": 1
- }
+ item.name: args
}, bom_no = self.bom_no)
def get_bom_raw_materials(self, qty):
@@ -1272,7 +1345,8 @@ class StockEntry(StockController):
item_dict[item]["qty"] = 0
# delete items with 0 qty
- for item in item_dict.keys():
+ list_of_items = item_dict.keys()
+ for item in list_of_items:
if not item_dict[item]["qty"]:
del item_dict[item]
@@ -1325,7 +1399,7 @@ class StockEntry(StockController):
se_child.is_scrap_item = item_dict[d].get("is_scrap_item", 0)
for field in ["idx", "po_detail", "original_item",
- "expense_account", "description", "item_name"]:
+ "expense_account", "description", "item_name", "serial_no", "batch_no"]:
if item_dict[d].get(field):
se_child.set(field, item_dict[d].get(field))
@@ -1378,33 +1452,26 @@ class StockEntry(StockController):
.format(item.batch_no, item.item_code))
def update_purchase_order_supplied_items(self):
- #Get PO Supplied Items Details
- item_wh = frappe._dict(frappe.db.sql("""
- select rm_item_code, reserve_warehouse
- from `tabPurchase Order` po, `tabPurchase Order Item Supplied` poitemsup
- where po.name = poitemsup.parent
- and po.name = %s""", self.purchase_order))
+ if (self.purchase_order and
+ (self.purpose in ['Send to Subcontractor', 'Material Transfer'] or self.is_return)):
- #Update Supplied Qty in PO Supplied Items
+ #Get PO Supplied Items Details
+ item_wh = frappe._dict(frappe.db.sql("""
+ select rm_item_code, reserve_warehouse
+ from `tabPurchase Order` po, `tabPurchase Order Item Supplied` poitemsup
+ where po.name = poitemsup.parent
+ and po.name = %s""", self.purchase_order))
- frappe.db.sql("""UPDATE `tabPurchase Order Item Supplied` pos
- SET
- pos.supplied_qty = IFNULL((SELECT ifnull(sum(transfer_qty), 0)
- FROM
- `tabStock Entry Detail` sed, `tabStock Entry` se
- WHERE
- pos.name = sed.po_detail AND pos.rm_item_code = sed.item_code
- AND pos.parent = se.purchase_order AND sed.docstatus = 1
- AND se.name = sed.parent and se.purchase_order = %(po)s
- ), 0)
- WHERE pos.docstatus = 1 and pos.parent = %(po)s""", {"po": self.purchase_order})
+ supplied_items = get_supplied_items(self.purchase_order)
+ for name, item in supplied_items.items():
+ frappe.db.set_value('Purchase Order Item Supplied', name, item)
- #Update reserved sub contracted quantity in bin based on Supplied Item Details and
- for d in self.get("items"):
- item_code = d.get('original_item') or d.get('item_code')
- reserve_warehouse = item_wh.get(item_code)
- stock_bin = get_bin(item_code, reserve_warehouse)
- stock_bin.update_reserved_qty_for_sub_contracting()
+ #Update reserved sub contracted quantity in bin based on Supplied Item Details and
+ for d in self.get("items"):
+ item_code = d.get('original_item') or d.get('item_code')
+ reserve_warehouse = item_wh.get(item_code)
+ stock_bin = get_bin(item_code, reserve_warehouse)
+ stock_bin.update_reserved_qty_for_sub_contracting()
def update_so_in_serial_number(self):
so_name, item_code = frappe.db.get_value("Work Order", self.work_order, ["sales_order", "production_item"])
@@ -1458,7 +1525,7 @@ class StockEntry(StockController):
cond += """ WHEN (parent = %s and name = %s) THEN %s
""" %(frappe.db.escape(data[0]), frappe.db.escape(data[1]), transferred_qty)
- if cond and stock_entries_child_list:
+ if stock_entries_child_list:
frappe.db.sql(""" UPDATE `tabStock Entry Detail`
SET
transferred_qty = CASE {cond} END
@@ -1509,6 +1576,36 @@ class StockEntry(StockController):
material_requests.append(material_request)
frappe.db.set_value('Material Request', material_request, 'transfer_status', status)
+ def set_serial_no_batch_for_finished_good(self):
+ args = {}
+ if self.pro_doc.serial_no:
+ self.get_serial_nos_for_fg(args)
+
+ for row in self.items:
+ if row.is_finished_item and row.item_code == self.pro_doc.production_item:
+ if args.get("serial_no"):
+ row.serial_no = '\n'.join(args["serial_no"][0: cint(row.qty)])
+
+ def get_serial_nos_for_fg(self, args):
+ fields = ["`tabStock Entry`.`name`", "`tabStock Entry Detail`.`qty`",
+ "`tabStock Entry Detail`.`serial_no`", "`tabStock Entry Detail`.`batch_no`"]
+
+ filters = [["Stock Entry","work_order","=",self.work_order], ["Stock Entry","purpose","=","Manufacture"],
+ ["Stock Entry","docstatus","=",1], ["Stock Entry Detail","item_code","=",self.pro_doc.production_item]]
+
+ stock_entries = frappe.get_all("Stock Entry", fields=fields, filters=filters)
+
+ if self.pro_doc.serial_no:
+ args["serial_no"] = self.get_available_serial_nos(stock_entries)
+
+ def get_available_serial_nos(self, stock_entries):
+ used_serial_nos = []
+ for row in stock_entries:
+ if row.serial_no:
+ used_serial_nos.extend(get_serial_nos(row.serial_no))
+
+ return sorted(list(set(get_serial_nos(self.pro_doc.serial_no)) - set(used_serial_nos)))
+
@frappe.whitelist()
def move_sample_to_retention_warehouse(company, items):
if isinstance(items, string_types):
@@ -1620,6 +1717,10 @@ def get_operating_cost_per_unit(work_order=None, bom_no=None):
if bom.quantity:
operating_cost_per_unit = flt(bom.operating_cost) / flt(bom.quantity)
+ if work_order and work_order.produced_qty and cint(frappe.db.get_single_value('Manufacturing Settings',
+ 'add_corrective_operation_cost_in_finished_good_valuation')):
+ operating_cost_per_unit += flt(work_order.corrective_operation_cost) / flt(work_order.produced_qty)
+
return operating_cost_per_unit
def get_used_alternative_items(purchase_order=None, work_order=None):
@@ -1688,7 +1789,7 @@ def get_expired_batch_items():
from `tabBatch` b, `tabStock Ledger Entry` sle
where b.expiry_date <= %s
and b.expiry_date is not NULL
- and b.batch_id = sle.batch_no
+ and b.batch_id = sle.batch_no and sle.is_cancelled = 0
group by sle.warehouse, sle.item_code, sle.batch_no""",(nowdate()), as_dict=1)
@frappe.whitelist()
@@ -1729,3 +1830,30 @@ def validate_sample_quantity(item_code, sample_quantity, qty, batch_no = None):
format(max_retain_qty, batch_no, item_code), alert=True)
sample_quantity = qty_diff
return sample_quantity
+
+def get_supplied_items(purchase_order):
+ fields = ['`tabStock Entry Detail`.`transfer_qty`', '`tabStock Entry`.`is_return`',
+ '`tabStock Entry Detail`.`po_detail`', '`tabStock Entry Detail`.`item_code`']
+
+ filters = [['Stock Entry', 'docstatus', '=', 1], ['Stock Entry', 'purchase_order', '=', purchase_order]]
+
+ supplied_item_details = {}
+ for row in frappe.get_all('Stock Entry', fields = fields, filters = filters):
+ if not row.po_detail:
+ continue
+
+ key = row.po_detail
+ if key not in supplied_item_details:
+ supplied_item_details.setdefault(key,
+ frappe._dict({'supplied_qty': 0, 'returned_qty':0, 'total_supplied_qty':0}))
+
+ supplied_item = supplied_item_details[key]
+
+ if row.is_return:
+ supplied_item.returned_qty += row.transfer_qty
+ else:
+ supplied_item.supplied_qty += row.transfer_qty
+
+ supplied_item.total_supplied_qty = flt(supplied_item.supplied_qty) - flt(supplied_item.returned_qty)
+
+ return supplied_item_details
\ No newline at end of file
diff --git a/erpnext/stock/doctype/stock_entry/stock_entry_utils.py b/erpnext/stock/doctype/stock_entry/stock_entry_utils.py
index b12a8547fea..563fcb03973 100644
--- a/erpnext/stock/doctype/stock_entry/stock_entry_utils.py
+++ b/erpnext/stock/doctype/stock_entry/stock_entry_utils.py
@@ -45,6 +45,8 @@ def make_stock_entry(**args):
s.posting_date = args.posting_date
if args.posting_time:
s.posting_time = args.posting_time
+ if args.inspection_required:
+ s.inspection_required = args.inspection_required
# map names
if args.from_warehouse:
diff --git a/erpnext/stock/doctype/stock_entry_detail/stock_entry_detail.json b/erpnext/stock/doctype/stock_entry_detail/stock_entry_detail.json
index 864ff488b22..22f412a2989 100644
--- a/erpnext/stock/doctype/stock_entry_detail/stock_entry_detail.json
+++ b/erpnext/stock/doctype/stock_entry_detail/stock_entry_detail.json
@@ -18,6 +18,7 @@
"col_break2",
"is_finished_item",
"is_scrap_item",
+ "quality_inspection",
"subcontracted_item",
"section_break_8",
"description",
@@ -69,7 +70,6 @@
"putaway_rule",
"column_break_51",
"reference_purchase_receipt",
- "quality_inspection",
"job_card_item"
],
"fields": [
@@ -307,6 +307,7 @@
"fieldname": "quality_inspection",
"fieldtype": "Link",
"label": "Quality Inspection",
+ "no_copy": 1,
"options": "Quality Inspection"
},
{
@@ -548,7 +549,7 @@
"index_web_pages_for_search": 1,
"istable": 1,
"links": [],
- "modified": "2021-02-11 13:47:50.158754",
+ "modified": "2021-06-21 16:03:18.834880",
"modified_by": "Administrator",
"module": "Stock",
"name": "Stock Entry Detail",
diff --git a/erpnext/stock/doctype/stock_entry_type/stock_entry_type.json b/erpnext/stock/doctype/stock_entry_type/stock_entry_type.json
index 0f2b55ec342..eee38be0278 100644
--- a/erpnext/stock/doctype/stock_entry_type/stock_entry_type.json
+++ b/erpnext/stock/doctype/stock_entry_type/stock_entry_type.json
@@ -6,7 +6,8 @@
"editable_grid": 1,
"engine": "InnoDB",
"field_order": [
- "purpose"
+ "purpose",
+ "add_to_transit"
],
"fields": [
{
@@ -18,10 +19,17 @@
"options": "\nMaterial Issue\nMaterial Receipt\nMaterial Transfer\nMaterial Transfer for Manufacture\nMaterial Consumption for Manufacture\nManufacture\nRepack\nSend to Subcontractor",
"reqd": 1,
"set_only_once": 1
+ },
+ {
+ "default": "0",
+ "depends_on": "eval: doc.purpose == 'Material Transfer'",
+ "fieldname": "add_to_transit",
+ "fieldtype": "Check",
+ "label": "Add to Transit"
}
],
"links": [],
- "modified": "2020-08-10 23:24:37.160817",
+ "modified": "2021-05-21 11:27:01.144110",
"modified_by": "Administrator",
"module": "Stock",
"name": "Stock Entry Type",
diff --git a/erpnext/stock/doctype/stock_entry_type/stock_entry_type.py b/erpnext/stock/doctype/stock_entry_type/stock_entry_type.py
index a4116aba2c2..1069ec8713e 100644
--- a/erpnext/stock/doctype/stock_entry_type/stock_entry_type.py
+++ b/erpnext/stock/doctype/stock_entry_type/stock_entry_type.py
@@ -7,4 +7,6 @@ from __future__ import unicode_literals
from frappe.model.document import Document
class StockEntryType(Document):
- pass
+ def validate(self):
+ if self.add_to_transit and self.purpose != 'Material Transfer':
+ self.add_to_transit = 0
diff --git a/erpnext/stock/doctype/stock_ledger_entry/stock_ledger_entry.py b/erpnext/stock/doctype/stock_ledger_entry/stock_ledger_entry.py
index b0e7440e6cc..b4f458388b3 100644
--- a/erpnext/stock/doctype/stock_ledger_entry/stock_ledger_entry.py
+++ b/erpnext/stock/doctype/stock_ledger_entry/stock_ledger_entry.py
@@ -5,7 +5,7 @@
from __future__ import unicode_literals
import frappe
from frappe import _
-from frappe.utils import flt, getdate, add_days, formatdate, get_datetime, date_diff
+from frappe.utils import flt, getdate, add_days, formatdate, get_datetime, cint
from frappe.model.document import Document
from datetime import date
from erpnext.controllers.item_variant import ItemTemplateCannotHaveStock
@@ -60,7 +60,7 @@ class StockLedgerEntry(Document):
if self.batch_no and not self.get("allow_negative_stock"):
batch_bal_after_transaction = flt(frappe.db.sql("""select sum(actual_qty)
from `tabStock Ledger Entry`
- where warehouse=%s and item_code=%s and batch_no=%s""",
+ where is_cancelled =0 and warehouse=%s and item_code=%s and batch_no=%s""",
(self.warehouse, self.item_code, self.batch_no))[0][0])
if batch_bal_after_transaction < 0:
@@ -89,17 +89,16 @@ class StockLedgerEntry(Document):
if item_det.is_stock_item != 1:
frappe.throw(_("Item {0} must be a stock Item").format(self.item_code))
- # check if batch number is required
- if self.voucher_type != 'Stock Reconciliation':
- if item_det.has_batch_no == 1:
- batch_item = self.item_code if self.item_code == item_det.item_name else self.item_code + ":" + item_det.item_name
- if not self.batch_no:
- frappe.throw(_("Batch number is mandatory for Item {0}").format(batch_item))
- elif not frappe.db.get_value("Batch",{"item": self.item_code, "name": self.batch_no}):
- frappe.throw(_("{0} is not a valid Batch Number for Item {1}").format(self.batch_no, batch_item))
+ # check if batch number is valid
+ if item_det.has_batch_no == 1:
+ batch_item = self.item_code if self.item_code == item_det.item_name else self.item_code + ":" + item_det.item_name
+ if not self.batch_no:
+ frappe.throw(_("Batch number is mandatory for Item {0}").format(batch_item))
+ elif not frappe.db.get_value("Batch",{"item": self.item_code, "name": self.batch_no}):
+ frappe.throw(_("{0} is not a valid Batch Number for Item {1}").format(self.batch_no, batch_item))
- elif item_det.has_batch_no == 0 and self.batch_no and self.is_cancelled == 0:
- frappe.throw(_("The Item {0} cannot have Batch").format(self.item_code))
+ elif item_det.has_batch_no == 0 and self.batch_no and self.is_cancelled == 0:
+ frappe.throw(_("The Item {0} cannot have Batch").format(self.item_code))
if item_det.has_variants:
frappe.throw(_("Stock cannot exist for Item {0} since has variants").format(self.item_code),
@@ -108,17 +107,18 @@ class StockLedgerEntry(Document):
self.stock_uom = item_det.stock_uom
def check_stock_frozen_date(self):
- stock_frozen_upto = frappe.db.get_value('Stock Settings', None, 'stock_frozen_upto') or ''
- if stock_frozen_upto:
- stock_auth_role = frappe.db.get_value('Stock Settings', None,'stock_auth_role')
- if getdate(self.posting_date) <= getdate(stock_frozen_upto) and not stock_auth_role in frappe.get_roles():
- frappe.throw(_("Stock transactions before {0} are frozen").format(formatdate(stock_frozen_upto)), StockFreezeError)
+ stock_settings = frappe.get_doc('Stock Settings', 'Stock Settings')
- stock_frozen_upto_days = int(frappe.db.get_value('Stock Settings', None, 'stock_frozen_upto_days') or 0)
+ if stock_settings.stock_frozen_upto:
+ if (getdate(self.posting_date) <= getdate(stock_settings.stock_frozen_upto)
+ and stock_settings.stock_auth_role not in frappe.get_roles()):
+ frappe.throw(_("Stock transactions before {0} are frozen")
+ .format(formatdate(stock_settings.stock_frozen_upto)), StockFreezeError)
+
+ stock_frozen_upto_days = cint(stock_settings.stock_frozen_upto_days)
if stock_frozen_upto_days:
- stock_auth_role = frappe.db.get_value('Stock Settings', None,'stock_auth_role')
older_than_x_days_ago = (add_days(getdate(self.posting_date), stock_frozen_upto_days) <= date.today())
- if older_than_x_days_ago and not stock_auth_role in frappe.get_roles():
+ if older_than_x_days_ago and stock_settings.stock_auth_role not in frappe.get_roles():
frappe.throw(_("Not allowed to update stock transactions older than {0}").format(stock_frozen_upto_days), StockFreezeError)
def scrub_posting_time(self):
@@ -152,7 +152,7 @@ class StockLedgerEntry(Document):
last_transaction_time = frappe.db.sql("""
select MAX(timestamp(posting_date, posting_time)) as posting_time
from `tabStock Ledger Entry`
- where docstatus = 1 and item_code = %s
+ where docstatus = 1 and is_cancelled = 0 and item_code = %s
and warehouse = %s""", (self.item_code, self.warehouse))[0][0]
cur_doc_posting_datetime = "%s %s" % (self.posting_date, self.get("posting_time") or "00:00:00")
@@ -177,3 +177,4 @@ def on_doctype_update():
frappe.db.add_index("Stock Ledger Entry", ["voucher_no", "voucher_type"])
frappe.db.add_index("Stock Ledger Entry", ["batch_no", "item_code", "warehouse"])
+ frappe.db.add_index("Stock Ledger Entry", ["voucher_detail_no"])
diff --git a/erpnext/stock/doctype/stock_ledger_entry/test_stock_ledger_entry.py b/erpnext/stock/doctype/stock_ledger_entry/test_stock_ledger_entry.py
index 349d8ae6794..af2ada8c9a4 100644
--- a/erpnext/stock/doctype/stock_ledger_entry/test_stock_ledger_entry.py
+++ b/erpnext/stock/doctype/stock_ledger_entry/test_stock_ledger_entry.py
@@ -15,10 +15,12 @@ from erpnext.stock.doctype.purchase_receipt.test_purchase_receipt import make_pu
from erpnext.stock.doctype.landed_cost_voucher.test_landed_cost_voucher import create_landed_cost_voucher
from erpnext.stock.doctype.delivery_note.test_delivery_note import create_delivery_note
from erpnext.stock.doctype.stock_ledger_entry.stock_ledger_entry import BackDatedStockTransaction
+from frappe.core.page.permission_manager.permission_manager import reset
class TestStockLedgerEntry(unittest.TestCase):
def setUp(self):
items = create_items()
+ reset('Stock Entry')
# delete SLE and BINs for all items
frappe.db.sql("delete from `tabStock Ledger Entry` where item_code in (%s)" % (', '.join(['%s']*len(items))), items)
@@ -34,7 +36,7 @@ class TestStockLedgerEntry(unittest.TestCase):
qty=50,
rate=100,
company=company,
- expense_account = "Stock Adjustment - _TC",
+ expense_account = "Stock Adjustment - _TC" if frappe.get_all("Stock Ledger Entry") else "Temporary Opening - _TC",
posting_date='2020-04-10',
posting_time='14:00'
)
@@ -46,51 +48,51 @@ class TestStockLedgerEntry(unittest.TestCase):
qty=10,
rate=200,
company=company,
- expense_account = "Stock Adjustment - _TC",
+ expense_account="Stock Adjustment - _TC" if frappe.get_all("Stock Ledger Entry") else "Temporary Opening - _TC",
posting_date='2020-04-20',
posting_time='14:00'
)
# _Test Item for Reposting transferred from Stores to FG warehouse on 30-04-2020
- make_stock_entry(
+ se = make_stock_entry(
item_code="_Test Item for Reposting",
source="Stores - _TC",
target="Finished Goods - _TC",
company=company,
qty=10,
- expense_account="Stock Adjustment - _TC",
+ expense_account="Stock Adjustment - _TC" if frappe.get_all("Stock Ledger Entry") else "Temporary Opening - _TC",
posting_date='2020-04-30',
posting_time='14:00'
)
- target_wh_sle = get_previous_sle({
+ target_wh_sle = frappe.db.get_value('Stock Ledger Entry', {
"item_code": "_Test Item for Reposting",
"warehouse": "Finished Goods - _TC",
- "posting_date": '2020-04-30',
- "posting_time": '14:00'
- })
+ "voucher_type": "Stock Entry",
+ "voucher_no": se.name
+ }, ["valuation_rate"], as_dict=1)
self.assertEqual(target_wh_sle.get("valuation_rate"), 150)
# Repack entry on 5-5-2020
repack = create_repack_entry(company=company, posting_date='2020-05-05', posting_time='14:00')
- finished_item_sle = get_previous_sle({
+ finished_item_sle = frappe.db.get_value('Stock Ledger Entry', {
"item_code": "_Test Finished Item for Reposting",
"warehouse": "Finished Goods - _TC",
- "posting_date": '2020-05-05',
- "posting_time": '14:00'
- })
+ "voucher_type": "Stock Entry",
+ "voucher_no": repack.name
+ }, ["incoming_rate", "valuation_rate"], as_dict=1)
self.assertEqual(finished_item_sle.get("incoming_rate"), 540)
self.assertEqual(finished_item_sle.get("valuation_rate"), 540)
# Reconciliation for _Test Item for Reposting at Stores on 12-04-2020: Qty = 50, Rate = 150
- create_stock_reconciliation(
+ sr = create_stock_reconciliation(
item_code="_Test Item for Reposting",
warehouse="Stores - _TC",
qty=50,
rate=150,
company=company,
- expense_account = "Stock Adjustment - _TC",
+ expense_account ="Stock Adjustment - _TC" if frappe.get_all("Stock Ledger Entry") else "Temporary Opening - _TC",
posting_date='2020-04-12',
posting_time='14:00'
)
@@ -107,12 +109,12 @@ class TestStockLedgerEntry(unittest.TestCase):
self.assertEqual(target_wh_sle.get("valuation_rate"), 175)
# Check valuation rate of repacked item after back-dated entry at Stores
- finished_item_sle = get_previous_sle({
+ finished_item_sle = frappe.db.get_value('Stock Ledger Entry', {
"item_code": "_Test Finished Item for Reposting",
"warehouse": "Finished Goods - _TC",
- "posting_date": '2020-05-05',
- "posting_time": '14:00'
- })
+ "voucher_type": "Stock Entry",
+ "voucher_no": repack.name
+ }, ["incoming_rate", "valuation_rate"], as_dict=1)
self.assertEqual(finished_item_sle.get("incoming_rate"), 790)
self.assertEqual(finished_item_sle.get("valuation_rate"), 790)
@@ -314,10 +316,11 @@ class TestStockLedgerEntry(unittest.TestCase):
# Set User with Stock User role but not Stock Manager
try:
user = frappe.get_doc("User", "test@example.com")
- frappe.set_user(user.name)
user.add_roles("Stock User")
user.remove_roles("Stock Manager")
+ frappe.set_user(user.name)
+
stock_entry_on_today = make_stock_entry(target="_Test Warehouse - _TC", qty=10, basic_rate=100)
back_dated_se_1 = make_stock_entry(target="_Test Warehouse - _TC", qty=10, basic_rate=100,
posting_date=add_days(today(), -1), do_not_submit=True)
diff --git a/erpnext/stock/doctype/stock_reconciliation/stock_reconciliation.js b/erpnext/stock/doctype/stock_reconciliation/stock_reconciliation.js
index ac4ed5e75d9..349e59f31d1 100644
--- a/erpnext/stock/doctype/stock_reconciliation/stock_reconciliation.js
+++ b/erpnext/stock/doctype/stock_reconciliation/stock_reconciliation.js
@@ -17,6 +17,14 @@ frappe.ui.form.on("Stock Reconciliation", {
}
}
});
+ frm.set_query("batch_no", "items", function(doc, cdt, cdn) {
+ var item = locals[cdt][cdn];
+ return {
+ filters: {
+ 'item': item.item_code
+ }
+ };
+ });
if (frm.doc.company) {
erpnext.queries.setup_queries(frm, "Warehouse", function() {
@@ -48,37 +56,54 @@ frappe.ui.form.on("Stock Reconciliation", {
},
get_items: function(frm) {
- frappe.prompt({label:"Warehouse", fieldname: "warehouse", fieldtype:"Link", options:"Warehouse", reqd: 1,
+ let fields = [{
+ label: 'Warehouse', fieldname: 'warehouse', fieldtype: 'Link', options: 'Warehouse', reqd: 1,
"get_query": function() {
return {
"filters": {
"company": frm.doc.company,
}
- }
- }},
- function(data) {
- frappe.call({
- method:"erpnext.stock.doctype.stock_reconciliation.stock_reconciliation.get_items",
- args: {
- warehouse: data.warehouse,
- posting_date: frm.doc.posting_date,
- posting_time: frm.doc.posting_time,
- company:frm.doc.company
- },
- callback: function(r) {
- var items = [];
- frm.clear_table("items");
- for(var i=0; i< r.message.length; i++) {
- var d = frm.add_child("items");
- $.extend(d, r.message[i]);
- if(!d.qty) d.qty = null;
- if(!d.valuation_rate) d.valuation_rate = null;
- }
- frm.refresh_field("items");
- }
- });
+ };
}
- , __("Get Items"), __("Update"));
+ }, {
+ label: "Item Code", fieldname: "item_code", fieldtype: "Link", options: "Item",
+ "get_query": function() {
+ return {
+ "filters": {
+ "disabled": 0,
+ }
+ };
+ }
+ }];
+
+ frappe.prompt(fields, function(data) {
+ frappe.call({
+ method: "erpnext.stock.doctype.stock_reconciliation.stock_reconciliation.get_items",
+ args: {
+ warehouse: data.warehouse,
+ posting_date: frm.doc.posting_date,
+ posting_time: frm.doc.posting_time,
+ company: frm.doc.company,
+ item_code: data.item_code
+ },
+ callback: function(r) {
+ frm.clear_table("items");
+ for (var i=0; i 100:
msgprint(_("The task has been enqueued as a background job. In case there is any issue on processing in background, the system will add a comment about the error on this Stock Reconciliation and revert to the Draft stage"))
- self.queue_action('submit')
+ self.queue_action('submit', timeout=2000)
else:
self._submit()
+ def cancel(self):
+ if len(self.items) > 100:
+ msgprint(_("The task has been enqueued as a background job. In case there is any issue on processing in background, the system will add a comment about the error on this Stock Reconciliation and revert to the Submitted stage"))
+ self.queue_action('cancel', timeout=2000)
+ else:
+ self._cancel()
+
@frappe.whitelist()
-def get_items(warehouse, posting_date, posting_time, company):
+def get_items(warehouse, posting_date, posting_time, company, item_code=None):
+ items = [frappe._dict({
+ 'item_code': item_code,
+ 'warehouse': warehouse
+ })]
+
+ if not item_code:
+ items = get_items_for_stock_reco(warehouse, company)
+
+ res = []
+ itemwise_batch_data = get_itemwise_batch(warehouse, posting_date, company, item_code)
+
+ for d in items:
+ if d.item_code in itemwise_batch_data:
+ stock_bal = get_stock_balance(d.item_code, d.warehouse,
+ posting_date, posting_time, with_valuation_rate=True)
+
+ for row in itemwise_batch_data.get(d.item_code):
+ args = get_item_data(row, row.qty, stock_bal[1])
+ res.append(args)
+ else:
+ stock_bal = get_stock_balance(d.item_code, d.warehouse, posting_date, posting_time,
+ with_valuation_rate=True , with_serial_no=cint(d.has_serial_no))
+
+ args = get_item_data(d, stock_bal[0], stock_bal[1],
+ stock_bal[2] if cint(d.has_serial_no) else '')
+
+ res.append(args)
+
+ return res
+
+def get_items_for_stock_reco(warehouse, company):
lft, rgt = frappe.db.get_value("Warehouse", warehouse, ["lft", "rgt"])
items = frappe.db.sql("""
- select i.name, i.item_name, bin.warehouse
+ select i.name as item_code, i.item_name, bin.warehouse as warehouse, i.has_serial_no, i.has_batch_no
from tabBin bin, tabItem i
- where i.name=bin.item_code and i.disabled=0 and i.is_stock_item = 1
- and i.has_variants = 0 and i.has_serial_no = 0 and i.has_batch_no = 0
- and exists(select name from `tabWarehouse` where lft >= %s and rgt <= %s and name=bin.warehouse)
- """, (lft, rgt))
+ where i.name=bin.item_code and IFNULL(i.disabled, 0) = 0 and i.is_stock_item = 1
+ and i.has_variants = 0 and exists(
+ select name from `tabWarehouse` where lft >= %s and rgt <= %s and name=bin.warehouse
+ )
+ """, (lft, rgt), as_dict=1)
items += frappe.db.sql("""
- select i.name, i.item_name, id.default_warehouse
+ select i.name as item_code, i.item_name, id.default_warehouse as warehouse, i.has_serial_no, i.has_batch_no
from tabItem i, `tabItem Default` id
where i.name = id.parent
and exists(select name from `tabWarehouse` where lft >= %s and rgt <= %s and name=id.default_warehouse)
- and i.is_stock_item = 1 and i.has_serial_no = 0 and i.has_batch_no = 0
- and i.has_variants = 0 and i.disabled = 0 and id.company=%s
+ and i.is_stock_item = 1 and i.has_variants = 0 and IFNULL(i.disabled, 0) = 0 and id.company=%s
group by i.name
- """, (lft, rgt, company))
+ """, (lft, rgt, company), as_dict=1)
- res = []
- for d in set(items):
- stock_bal = get_stock_balance(d[0], d[2], posting_date, posting_time,
- with_valuation_rate=True)
+ return items
- if frappe.db.get_value("Item", d[0], "disabled") == 0:
- res.append({
- "item_code": d[0],
- "warehouse": d[2],
- "qty": stock_bal[0],
- "item_name": d[1],
- "valuation_rate": stock_bal[1],
- "current_qty": stock_bal[0],
- "current_valuation_rate": stock_bal[1]
- })
+def get_item_data(row, qty, valuation_rate, serial_no=None):
+ return {
+ 'item_code': row.item_code,
+ 'warehouse': row.warehouse,
+ 'qty': qty,
+ 'item_name': row.item_name,
+ 'valuation_rate': valuation_rate,
+ 'current_qty': qty,
+ 'current_valuation_rate': valuation_rate,
+ 'current_serial_no': serial_no,
+ 'serial_no': serial_no,
+ 'batch_no': row.get('batch_no')
+ }
- return res
+def get_itemwise_batch(warehouse, posting_date, company, item_code=None):
+ from erpnext.stock.report.batch_wise_balance_history.batch_wise_balance_history import execute
+ itemwise_batch_data = {}
+
+ filters = frappe._dict({
+ 'warehouse': warehouse,
+ 'from_date': posting_date,
+ 'to_date': posting_date,
+ 'company': company
+ })
+
+ if item_code:
+ filters.item_code = item_code
+
+ columns, data = execute(filters)
+
+ for row in data:
+ itemwise_batch_data.setdefault(row[0], []).append(frappe._dict({
+ 'item_code': row[0],
+ 'warehouse': warehouse,
+ 'qty': row[8],
+ 'item_name': row[1],
+ 'batch_no': row[4]
+ }))
+
+ return itemwise_batch_data
@frappe.whitelist()
def get_stock_balance_for(item_code, warehouse,
diff --git a/erpnext/stock/doctype/stock_reconciliation/test_stock_reconciliation.py b/erpnext/stock/doctype/stock_reconciliation/test_stock_reconciliation.py
index 6690c6a606c..c192582531a 100644
--- a/erpnext/stock/doctype/stock_reconciliation/test_stock_reconciliation.py
+++ b/erpnext/stock/doctype/stock_reconciliation/test_stock_reconciliation.py
@@ -6,7 +6,7 @@
from __future__ import unicode_literals
import frappe, unittest
-from frappe.utils import flt, nowdate, nowtime
+from frappe.utils import flt, nowdate, nowtime, random_string, add_days
from erpnext.accounts.utils import get_stock_and_account_balance
from erpnext.stock.stock_ledger import get_previous_sle, update_entries_after
from erpnext.stock.doctype.stock_reconciliation.stock_reconciliation import EmptyStockReconciliationItemsError, get_items
@@ -14,6 +14,8 @@ from erpnext.stock.doctype.warehouse.test_warehouse import create_warehouse
from erpnext.stock.doctype.item.test_item import create_item
from erpnext.stock.utils import get_incoming_rate, get_stock_value_on, get_valuation_method
from erpnext.stock.doctype.serial_no.serial_no import get_serial_nos
+from erpnext.stock.doctype.purchase_receipt.test_purchase_receipt import make_purchase_receipt
+
class TestStockReconciliation(unittest.TestCase):
@classmethod
@@ -32,7 +34,7 @@ class TestStockReconciliation(unittest.TestCase):
company = frappe.db.get_value('Warehouse', 'Stores - TCP1', 'company')
# [[qty, valuation_rate, posting_date,
# posting_time, expected_stock_value, bin_qty, bin_valuation]]
-
+
input_data = [
[50, 1000, "2012-12-26", "12:00"],
[25, 900, "2012-12-26", "12:00"],
@@ -86,7 +88,7 @@ class TestStockReconciliation(unittest.TestCase):
se1.cancel()
def test_get_items(self):
- create_warehouse("_Test Warehouse Group 1",
+ create_warehouse("_Test Warehouse Group 1",
{"is_group": 1, "company": "_Test Company", "parent_warehouse": "All Warehouses - _TC"})
create_warehouse("_Test Warehouse Ledger 1",
{"is_group": 0, "parent_warehouse": "_Test Warehouse Group 1 - _TC", "company": "_Test Company"})
@@ -150,6 +152,42 @@ class TestStockReconciliation(unittest.TestCase):
stock_doc = frappe.get_doc("Stock Reconciliation", d)
stock_doc.cancel()
+
+ def test_stock_reco_for_merge_serialized_item(self):
+ to_delete_records = []
+
+ # Add new serial nos
+ serial_item_code = "Stock-Reco-Serial-Item-2"
+ serial_warehouse = "_Test Warehouse for Stock Reco1 - _TC"
+
+ sr = create_stock_reconciliation(item_code=serial_item_code, serial_no=random_string(6),
+ warehouse = serial_warehouse, qty=1, rate=100, do_not_submit=True, purpose='Opening Stock')
+
+ for i in range(3):
+ sr.append('items', {
+ 'item_code': serial_item_code,
+ 'warehouse': serial_warehouse,
+ 'qty': 1,
+ 'valuation_rate': 100,
+ 'serial_no': random_string(6)
+ })
+
+ sr.save()
+ sr.submit()
+
+ sle_entries = frappe.get_all('Stock Ledger Entry', filters= {'voucher_no': sr.name},
+ fields = ['name', 'incoming_rate'])
+
+ self.assertEqual(len(sle_entries), 1)
+ self.assertEqual(sle_entries[0].incoming_rate, 100)
+
+ to_delete_records.append(sr.name)
+ to_delete_records.reverse()
+
+ for d in to_delete_records:
+ stock_doc = frappe.get_doc("Stock Reconciliation", d)
+ stock_doc.cancel()
+
def test_stock_reco_for_batch_item(self):
to_delete_records = []
to_delete_serial_nos = []
@@ -204,6 +242,137 @@ class TestStockReconciliation(unittest.TestCase):
self.assertEqual(sr.get("items")[0].valuation_rate, 0)
self.assertEqual(sr.get("items")[0].amount, 0)
+ def test_backdated_stock_reco_qty_reposting(self):
+ """
+ Test if a backdated stock reco recalculates future qty until next reco.
+ -------------------------------------------
+ Var | Doc | Qty | Balance
+ -------------------------------------------
+ SR5 | Reco | 0 | 8 (posting date: today-4) [backdated]
+ PR1 | PR | 10 | 18 (posting date: today-3)
+ PR2 | PR | 1 | 19 (posting date: today-2)
+ SR4 | Reco | 0 | 6 (posting date: today-1) [backdated]
+ PR3 | PR | 1 | 7 (posting date: today) # can't post future PR
+ """
+ item_code = "Backdated-Reco-Item"
+ warehouse = "_Test Warehouse - _TC"
+ create_item(item_code)
+
+ pr1 = make_purchase_receipt(item_code=item_code, warehouse=warehouse, qty=10, rate=100,
+ posting_date=add_days(nowdate(), -3))
+ pr2 = make_purchase_receipt(item_code=item_code, warehouse=warehouse, qty=1, rate=100,
+ posting_date=add_days(nowdate(), -2))
+ pr3 = make_purchase_receipt(item_code=item_code, warehouse=warehouse, qty=1, rate=100,
+ posting_date=nowdate())
+
+ pr1_balance = frappe.db.get_value("Stock Ledger Entry", {"voucher_no": pr1.name, "is_cancelled": 0},
+ "qty_after_transaction")
+ pr3_balance = frappe.db.get_value("Stock Ledger Entry", {"voucher_no": pr3.name, "is_cancelled": 0},
+ "qty_after_transaction")
+ self.assertEqual(pr1_balance, 10)
+ self.assertEqual(pr3_balance, 12)
+
+ # post backdated stock reco in between
+ sr4 = create_stock_reconciliation(item_code=item_code, warehouse=warehouse, qty=6, rate=100,
+ posting_date=add_days(nowdate(), -1))
+ pr3_balance = frappe.db.get_value("Stock Ledger Entry", {"voucher_no": pr3.name, "is_cancelled": 0},
+ "qty_after_transaction")
+ self.assertEqual(pr3_balance, 7)
+
+ # post backdated stock reco at the start
+ sr5 = create_stock_reconciliation(item_code=item_code, warehouse=warehouse, qty=8, rate=100,
+ posting_date=add_days(nowdate(), -4))
+ pr1_balance = frappe.db.get_value("Stock Ledger Entry", {"voucher_no": pr1.name, "is_cancelled": 0},
+ "qty_after_transaction")
+ pr2_balance = frappe.db.get_value("Stock Ledger Entry", {"voucher_no": pr2.name, "is_cancelled": 0},
+ "qty_after_transaction")
+ sr4_balance = frappe.db.get_value("Stock Ledger Entry", {"voucher_no": sr4.name, "is_cancelled": 0},
+ "qty_after_transaction")
+ self.assertEqual(pr1_balance, 18)
+ self.assertEqual(pr2_balance, 19)
+ self.assertEqual(sr4_balance, 6) # check if future stock reco is unaffected
+
+ # cancel backdated stock reco and check future impact
+ sr5.cancel()
+ pr1_balance = frappe.db.get_value("Stock Ledger Entry", {"voucher_no": pr1.name, "is_cancelled": 0},
+ "qty_after_transaction")
+ pr2_balance = frappe.db.get_value("Stock Ledger Entry", {"voucher_no": pr2.name, "is_cancelled": 0},
+ "qty_after_transaction")
+ sr4_balance = frappe.db.get_value("Stock Ledger Entry", {"voucher_no": sr4.name, "is_cancelled": 0},
+ "qty_after_transaction")
+ self.assertEqual(pr1_balance, 10)
+ self.assertEqual(pr2_balance, 11)
+ self.assertEqual(sr4_balance, 6) # check if future stock reco is unaffected
+
+ # teardown
+ sr4.cancel()
+ pr3.cancel()
+ pr2.cancel()
+ pr1.cancel()
+
+ def test_backdated_stock_reco_future_negative_stock(self):
+ """
+ Test if a backdated stock reco causes future negative stock and is blocked.
+ -------------------------------------------
+ Var | Doc | Qty | Balance
+ -------------------------------------------
+ PR1 | PR | 10 | 10 (posting date: today-2)
+ SR3 | Reco | 0 | 1 (posting date: today-1) [backdated & blocked]
+ DN2 | DN | -2 | 8(-1) (posting date: today)
+ """
+ from erpnext.stock.stock_ledger import NegativeStockError
+ from erpnext.stock.doctype.delivery_note.test_delivery_note import create_delivery_note
+
+ item_code = "Backdated-Reco-Item"
+ warehouse = "_Test Warehouse - _TC"
+ create_item(item_code)
+
+ negative_stock_setting = frappe.db.get_single_value("Stock Settings", "allow_negative_stock")
+ frappe.db.set_value("Stock Settings", None, "allow_negative_stock", 0)
+
+ pr1 = make_purchase_receipt(item_code=item_code, warehouse=warehouse, qty=10, rate=100,
+ posting_date=add_days(nowdate(), -2))
+ dn2 = create_delivery_note(item_code=item_code, warehouse=warehouse, qty=2, rate=120,
+ posting_date=nowdate())
+
+ pr1_balance = frappe.db.get_value("Stock Ledger Entry", {"voucher_no": pr1.name, "is_cancelled": 0},
+ "qty_after_transaction")
+ dn2_balance = frappe.db.get_value("Stock Ledger Entry", {"voucher_no": dn2.name, "is_cancelled": 0},
+ "qty_after_transaction")
+ self.assertEqual(pr1_balance, 10)
+ self.assertEqual(dn2_balance, 8)
+
+ # check if stock reco is blocked
+ sr3 = create_stock_reconciliation(item_code=item_code, warehouse=warehouse, qty=1, rate=100,
+ posting_date=add_days(nowdate(), -1), do_not_submit=True)
+ self.assertRaises(NegativeStockError, sr3.submit)
+
+ # teardown
+ frappe.db.set_value("Stock Settings", None, "allow_negative_stock", negative_stock_setting)
+ sr3.cancel()
+ dn2.cancel()
+ pr1.cancel()
+
+ def test_valid_batch(self):
+ create_batch_item_with_batch("Testing Batch Item 1", "001")
+ create_batch_item_with_batch("Testing Batch Item 2", "002")
+ sr = create_stock_reconciliation(item_code="Testing Batch Item 1", qty=1, rate=100, batch_no="002"
+ , do_not_submit=True)
+ self.assertRaises(frappe.ValidationError, sr.submit)
+
+def create_batch_item_with_batch(item_name, batch_id):
+ batch_item_doc = create_item(item_name, is_stock_item=1)
+ if not batch_item_doc.has_batch_no:
+ batch_item_doc.has_batch_no = 1
+ batch_item_doc.create_new_batch = 1
+ batch_item_doc.save(ignore_permissions=True)
+
+ if not frappe.db.exists('Batch', batch_id):
+ b = frappe.new_doc('Batch')
+ b.item = item_name
+ b.batch_id = batch_id
+ b.save()
+
def insert_existing_sle(warehouse):
from erpnext.stock.doctype.stock_entry.test_stock_entry import make_stock_entry
@@ -231,6 +400,12 @@ def create_batch_or_serial_no_items():
serial_item_doc.serial_no_series = "SRSI.####"
serial_item_doc.save(ignore_permissions=True)
+ serial_item_doc = create_item("Stock-Reco-Serial-Item-2", is_stock_item=1)
+ if not serial_item_doc.has_serial_no:
+ serial_item_doc.has_serial_no = 1
+ serial_item_doc.serial_no_series = "SRSII.####"
+ serial_item_doc.save(ignore_permissions=True)
+
batch_item_doc = create_item("Stock-Reco-batch-Item-1", is_stock_item=1)
if not batch_item_doc.has_batch_no:
batch_item_doc.has_batch_no = 1
diff --git a/erpnext/stock/doctype/stock_reconciliation_item/stock_reconciliation_item.json b/erpnext/stock/doctype/stock_reconciliation_item/stock_reconciliation_item.json
index 85c7ebe2634..6bbba051f98 100644
--- a/erpnext/stock/doctype/stock_reconciliation_item/stock_reconciliation_item.json
+++ b/erpnext/stock/doctype/stock_reconciliation_item/stock_reconciliation_item.json
@@ -1,4 +1,5 @@
{
+ "actions": [],
"creation": "2015-02-17 01:06:05.072764",
"doctype": "DocType",
"document_type": "Other",
@@ -170,6 +171,7 @@
},
{
"default": "0",
+ "depends_on": "allow_zero_valuation_rate",
"fieldname": "allow_zero_valuation_rate",
"fieldtype": "Check",
"label": "Allow Zero Valuation Rate",
@@ -179,7 +181,7 @@
],
"istable": 1,
"links": [],
- "modified": "2021-03-23 11:09:44.407157",
+ "modified": "2021-05-21 12:13:33.041266",
"modified_by": "Administrator",
"module": "Stock",
"name": "Stock Reconciliation Item",
@@ -189,4 +191,4 @@
"sort_field": "modified",
"sort_order": "DESC",
"track_changes": 1
-}
+}
\ No newline at end of file
diff --git a/erpnext/stock/doctype/stock_settings/stock_settings.json b/erpnext/stock/doctype/stock_settings/stock_settings.json
index 84af57b48dd..2a9dcfb67ed 100644
--- a/erpnext/stock/doctype/stock_settings/stock_settings.json
+++ b/erpnext/stock/doctype/stock_settings/stock_settings.json
@@ -5,39 +5,47 @@
"doctype": "DocType",
"engine": "InnoDB",
"field_order": [
+ "item_defaults_section",
"item_naming_by",
"item_group",
"stock_uom",
"default_warehouse",
- "sample_retention_warehouse",
"column_break_4",
"valuation_method",
+ "sample_retention_warehouse",
+ "use_naming_series",
+ "naming_series_prefix",
+ "section_break_9",
"over_delivery_receipt_allowance",
- "action_if_quality_inspection_is_not_submitted",
- "show_barcode_field",
- "clean_description_html",
- "disable_serial_no_and_batch_selector",
- "section_break_7",
+ "role_allowed_to_over_deliver_receive",
+ "column_break_12",
"auto_insert_price_list_rate_if_missing",
"allow_negative_stock",
- "column_break_10",
+ "show_barcode_field",
+ "clean_description_html",
+ "quality_inspection_settings_section",
+ "action_if_quality_inspection_is_not_submitted",
+ "column_break_21",
+ "action_if_quality_inspection_is_rejected",
+ "section_break_7",
"automatically_set_serial_nos_based_on_fifo",
"set_qty_in_transactions_based_on_serial_no_input",
+ "column_break_10",
+ "disable_serial_no_and_batch_selector",
"auto_material_request",
"auto_indent",
+ "column_break_27",
"reorder_email_notify",
"inter_warehouse_transfer_settings_section",
"allow_from_dn",
+ "column_break_31",
"allow_from_pr",
"control_historical_stock_transactions_section",
- "role_allowed_to_create_edit_back_dated_transactions",
- "column_break_26",
"stock_frozen_upto",
"stock_frozen_upto_days",
- "stock_auth_role",
- "batch_id_sb",
- "use_naming_series",
- "naming_series_prefix"
+ "column_break_26",
+ "role_allowed_to_create_edit_back_dated_transactions",
+ "stock_auth_role"
],
"fields": [
{
@@ -101,23 +109,24 @@
"default": "1",
"fieldname": "show_barcode_field",
"fieldtype": "Check",
- "label": "Show Barcode Field"
+ "label": "Show Barcode Field in Stock Transactions"
},
{
"default": "1",
"fieldname": "clean_description_html",
"fieldtype": "Check",
- "label": "Convert Item Description to Clean HTML"
+ "label": "Convert Item Description to Clean HTML in Transactions"
},
{
"fieldname": "section_break_7",
- "fieldtype": "Section Break"
+ "fieldtype": "Section Break",
+ "label": "Serialised and Batch Setting"
},
{
"default": "0",
"fieldname": "auto_insert_price_list_rate_if_missing",
"fieldtype": "Check",
- "label": "Auto Insert Price List Rate If Missing"
+ "label": "Auto Insert Item Price If Missing"
},
{
"default": "0",
@@ -178,16 +187,11 @@
"label": "Role Allowed to Edit Frozen Stock",
"options": "Role"
},
- {
- "fieldname": "batch_id_sb",
- "fieldtype": "Section Break",
- "label": "Batch Identification"
- },
{
"default": "0",
"fieldname": "use_naming_series",
"fieldtype": "Check",
- "label": "Use Naming Series"
+ "label": "Have Default Naming Series for Batch ID?"
},
{
"default": "BATCH-",
@@ -234,6 +238,51 @@
"fieldname": "disable_serial_no_and_batch_selector",
"fieldtype": "Check",
"label": "Disable Serial No And Batch Selector"
+ },
+ {
+ "description": "Users with this role are allowed to over deliver/receive against orders above the allowance percentage",
+ "fieldname": "role_allowed_to_over_deliver_receive",
+ "fieldtype": "Link",
+ "label": "Role Allowed to Over Deliver/Receive",
+ "options": "Role"
+ },
+ {
+ "fieldname": "item_defaults_section",
+ "fieldtype": "Section Break",
+ "label": "Item Defaults"
+ },
+ {
+ "fieldname": "section_break_9",
+ "fieldtype": "Section Break",
+ "label": "Stock Transactions Settings"
+ },
+ {
+ "fieldname": "column_break_12",
+ "fieldtype": "Column Break"
+ },
+ {
+ "fieldname": "column_break_27",
+ "fieldtype": "Column Break"
+ },
+ {
+ "fieldname": "column_break_31",
+ "fieldtype": "Column Break"
+ },
+ {
+ "fieldname": "quality_inspection_settings_section",
+ "fieldtype": "Section Break",
+ "label": "Quality Inspection Settings"
+ },
+ {
+ "fieldname": "column_break_21",
+ "fieldtype": "Column Break"
+ },
+ {
+ "default": "Stop",
+ "fieldname": "action_if_quality_inspection_is_rejected",
+ "fieldtype": "Select",
+ "label": "Action If Quality Inspection Is Rejected",
+ "options": "Stop\nWarn"
}
],
"icon": "icon-cog",
@@ -241,7 +290,7 @@
"index_web_pages_for_search": 1,
"issingle": 1,
"links": [],
- "modified": "2021-01-18 13:15:38.352796",
+ "modified": "2021-07-10 16:17:42.159829",
"modified_by": "Administrator",
"module": "Stock",
"name": "Stock Settings",
diff --git a/erpnext/stock/doctype/stock_settings/stock_settings.py b/erpnext/stock/doctype/stock_settings/stock_settings.py
index 3b9608b8056..2dd7c6f35b8 100644
--- a/erpnext/stock/doctype/stock_settings/stock_settings.py
+++ b/erpnext/stock/doctype/stock_settings/stock_settings.py
@@ -30,7 +30,7 @@ class StockSettings(Document):
# show/hide barcode field
for name in ["barcode", "barcodes", "scan_barcode"]:
frappe.make_property_setter({'fieldname': name, 'property': 'hidden',
- 'value': 0 if self.show_barcode_field else 1})
+ 'value': 0 if self.show_barcode_field else 1}, validate_fields_for_doctype=False)
self.validate_warehouses()
self.cant_change_valuation_method()
@@ -67,10 +67,10 @@ class StockSettings(Document):
self.toggle_warehouse_field_for_inter_warehouse_transfer()
def toggle_warehouse_field_for_inter_warehouse_transfer(self):
- make_property_setter("Sales Invoice Item", "target_warehouse", "hidden", 1 - cint(self.allow_from_dn), "Check")
- make_property_setter("Delivery Note Item", "target_warehouse", "hidden", 1 - cint(self.allow_from_dn), "Check")
- make_property_setter("Purchase Invoice Item", "from_warehouse", "hidden", 1 - cint(self.allow_from_pr), "Check")
- make_property_setter("Purchase Receipt Item", "from_warehouse", "hidden", 1 - cint(self.allow_from_pr), "Check")
+ make_property_setter("Sales Invoice Item", "target_warehouse", "hidden", 1 - cint(self.allow_from_dn), "Check", validate_fields_for_doctype=False)
+ make_property_setter("Delivery Note Item", "target_warehouse", "hidden", 1 - cint(self.allow_from_dn), "Check", validate_fields_for_doctype=False)
+ make_property_setter("Purchase Invoice Item", "from_warehouse", "hidden", 1 - cint(self.allow_from_pr), "Check", validate_fields_for_doctype=False)
+ make_property_setter("Purchase Receipt Item", "from_warehouse", "hidden", 1 - cint(self.allow_from_pr), "Check", validate_fields_for_doctype=False)
def clean_all_descriptions():
diff --git a/erpnext/stock/doctype/warehouse/test_warehouse.py b/erpnext/stock/doctype/warehouse/test_warehouse.py
index 95478f61f0a..e3981c913e1 100644
--- a/erpnext/stock/doctype/warehouse/test_warehouse.py
+++ b/erpnext/stock/doctype/warehouse/test_warehouse.py
@@ -11,6 +11,7 @@ from frappe.test_runner import make_test_records
import erpnext
from erpnext.stock.doctype.stock_entry.stock_entry_utils import make_stock_entry
from erpnext.accounts.doctype.account.test_account import get_inventory_account, create_account
+from erpnext.stock.doctype.item.test_item import create_item
test_records = frappe.get_test_records('Warehouse')
@@ -92,6 +93,39 @@ class TestWarehouse(unittest.TestCase):
self.assertTrue(frappe.db.get_value("Warehouse",
filters={"account": "Test Warehouse for Merging 2 - TCP1"}))
+ def test_unlinking_warehouse_from_item_defaults(self):
+ company = "_Test Company"
+
+ warehouse_names = [f'_Test Warehouse {i} for Unlinking' for i in range(2)]
+ warehouse_ids = []
+ for warehouse in warehouse_names:
+ warehouse_id = create_warehouse(warehouse, company=company)
+ warehouse_ids.append(warehouse_id)
+
+ item_names = [f'_Test Item {i} for Unlinking' for i in range(2)]
+ for item, warehouse in zip(item_names, warehouse_ids):
+ create_item(item, warehouse=warehouse, company=company)
+
+ # Delete warehouses
+ for warehouse in warehouse_ids:
+ frappe.delete_doc("Warehouse", warehouse)
+
+ # Check Item existance
+ for item in item_names:
+ self.assertTrue(
+ bool(frappe.db.exists("Item", item)),
+ f"{item} doesn't exist"
+ )
+
+ item_doc = frappe.get_doc("Item", item)
+ for item_default in item_doc.item_defaults:
+ self.assertNotIn(
+ item_default.default_warehouse,
+ warehouse_ids,
+ f"{item} linked to {item_default.default_warehouse} in {warehouse_ids}."
+ )
+
+
def create_warehouse(warehouse_name, properties=None, company=None):
if not company:
company = "_Test Company"
diff --git a/erpnext/stock/doctype/warehouse/warehouse.json b/erpnext/stock/doctype/warehouse/warehouse.json
index bddb114c9de..9b9093261c2 100644
--- a/erpnext/stock/doctype/warehouse/warehouse.json
+++ b/erpnext/stock/doctype/warehouse/warehouse.json
@@ -70,6 +70,7 @@
"oldfieldname": "company",
"oldfieldtype": "Link",
"options": "Company",
+ "read_only_depends_on": "eval: !doc.__islocal",
"remember_last_selected_value": 1,
"reqd": 1,
"search_index": 1
@@ -244,7 +245,7 @@
"idx": 1,
"is_tree": 1,
"links": [],
- "modified": "2021-02-16 17:21:52.380098",
+ "modified": "2021-04-09 19:54:56.263965",
"modified_by": "Administrator",
"module": "Stock",
"name": "Warehouse",
diff --git a/erpnext/stock/doctype/warehouse/warehouse.py b/erpnext/stock/doctype/warehouse/warehouse.py
index 6c84f168fd4..3abc13907cf 100644
--- a/erpnext/stock/doctype/warehouse/warehouse.py
+++ b/erpnext/stock/doctype/warehouse/warehouse.py
@@ -3,8 +3,9 @@
from __future__ import unicode_literals
import frappe, erpnext
-from frappe.utils import cint, nowdate
+from frappe.utils import cint, flt
from frappe import throw, _
+from collections import defaultdict
from frappe.utils.nestedset import NestedSet
from erpnext.stock import get_warehouse_account
from frappe.contacts.address_and_contact import load_address_and_contact
@@ -53,6 +54,7 @@ class Warehouse(NestedSet):
throw(_("Child warehouse exists for this warehouse. You can not delete this warehouse."))
self.update_nsm_model()
+ self.unlink_from_items()
def check_if_sle_exists(self):
return frappe.db.sql("""select name from `tabStock Ledger Entry`
@@ -137,10 +139,14 @@ class Warehouse(NestedSet):
self.save()
return 1
+ def unlink_from_items(self):
+ frappe.db.sql("""
+ update `tabItem Default`
+ set default_warehouse=NULL
+ where default_warehouse=%s""", self.name)
+
@frappe.whitelist()
def get_children(doctype, parent=None, company=None, is_root=False):
- from erpnext.stock.utils import get_stock_value_from_bin
-
if is_root:
parent = ""
@@ -153,13 +159,48 @@ def get_children(doctype, parent=None, company=None, is_root=False):
warehouses = frappe.get_list(doctype, fields=fields, filters=filters, order_by='name')
+ company_currency = ''
+ if company:
+ company_currency = frappe.get_cached_value('Company', company, 'default_currency')
+
+ warehouse_wise_value = get_warehouse_wise_stock_value(company)
+
# return warehouses
for wh in warehouses:
- wh["balance"] = get_stock_value_from_bin(warehouse=wh.value)
- if company:
- wh["company_currency"] = frappe.db.get_value('Company', company, 'default_currency')
+ wh["balance"] = warehouse_wise_value.get(wh.value)
+ if company_currency:
+ wh["company_currency"] = company_currency
return warehouses
+def get_warehouse_wise_stock_value(company):
+ warehouses = frappe.get_all('Warehouse',
+ fields = ['name', 'parent_warehouse'], filters = {'company': company})
+ parent_warehouse = {d.name : d.parent_warehouse for d in warehouses}
+
+ filters = {'warehouse': ('in', [data.name for data in warehouses])}
+ bin_data = frappe.get_all('Bin', fields = ['sum(stock_value) as stock_value', 'warehouse'],
+ filters = filters, group_by = 'warehouse')
+
+ warehouse_wise_stock_value = defaultdict(float)
+ for row in bin_data:
+ if not row.stock_value:
+ continue
+
+ warehouse_wise_stock_value[row.warehouse] = row.stock_value
+ update_value_in_parent_warehouse(warehouse_wise_stock_value,
+ parent_warehouse, row.warehouse, row.stock_value)
+
+ return warehouse_wise_stock_value
+
+def update_value_in_parent_warehouse(warehouse_wise_stock_value, parent_warehouse_dict, warehouse, stock_value):
+ parent_warehouse = parent_warehouse_dict.get(warehouse)
+ if not parent_warehouse:
+ return
+
+ warehouse_wise_stock_value[parent_warehouse] += flt(stock_value)
+ update_value_in_parent_warehouse(warehouse_wise_stock_value, parent_warehouse_dict,
+ parent_warehouse, stock_value)
+
@frappe.whitelist()
def add_node():
from frappe.desk.treeview import make_tree_args
diff --git a/erpnext/stock/doctype/warehouse/warehouse_tree.js b/erpnext/stock/doctype/warehouse/warehouse_tree.js
index 3665c0530f2..407d7d1ccd5 100644
--- a/erpnext/stock/doctype/warehouse/warehouse_tree.js
+++ b/erpnext/stock/doctype/warehouse/warehouse_tree.js
@@ -20,7 +20,7 @@ frappe.treeview_settings['Warehouse'] = {
onrender: function(node) {
if (node.data && node.data.balance!==undefined) {
$(''
- + format_currency(Math.abs(node.data.balance), node.data.company_currency)
+ + format_currency((node.data.balance), node.data.company_currency)
+ '').insertBefore(node.$ul);
}
}
diff --git a/erpnext/stock/get_item_details.py b/erpnext/stock/get_item_details.py
index e23f7d43d9d..cf52803fca8 100644
--- a/erpnext/stock/get_item_details.py
+++ b/erpnext/stock/get_item_details.py
@@ -74,19 +74,18 @@ def get_item_details(args, doc=None, for_validate=False, overwrite_warehouse=Tru
update_party_blanket_order(args, out)
- if not doc or cint(doc.get('is_return')) == 0:
- # get price list rate only if the invoice is not a credit or debit note
- get_price_list_rate(args, item, out)
+
+ get_price_list_rate(args, item, out)
if args.customer and cint(args.is_pos):
- out.update(get_pos_profile_item_details(args.company, args))
+ out.update(get_pos_profile_item_details(args.company, args, update_data=True))
if (args.get("doctype") == "Material Request" and
args.get("material_request_type") == "Material Transfer"):
out.update(get_bin_details(args.item_code, args.get("from_warehouse")))
elif out.get("warehouse"):
- out.update(get_bin_details(args.item_code, out.warehouse))
+ out.update(get_bin_details(args.item_code, out.warehouse, args.company))
# update args with out, if key or value not exists
for key, value in iteritems(out):
@@ -309,8 +308,6 @@ def get_basic_details(args, item, overwrite_warehouse=True):
"update_stock": args.get("update_stock") if args.get('doctype') in ['Sales Invoice', 'Purchase Invoice'] else 0,
"delivered_by_supplier": item.delivered_by_supplier if args.get("doctype") in ["Sales Order", "Sales Invoice"] else 0,
"is_fixed_asset": item.is_fixed_asset,
- "weight_per_unit":item.weight_per_unit,
- "weight_uom":item.weight_uom,
"last_purchase_rate": item.last_purchase_rate if args.get("doctype") in ["Purchase Order"] else 0,
"transaction_date": args.get("transaction_date"),
"against_blanket_order": args.get("against_blanket_order"),
@@ -438,18 +435,37 @@ def get_barcode_data(items_list):
return itemwise_barcode
@frappe.whitelist()
-def get_item_tax_info(company, tax_category, item_codes):
+def get_item_tax_info(company, tax_category, item_codes, item_rates=None, item_tax_templates=None):
out = {}
- if isinstance(item_codes, string_types):
+
+ if item_tax_templates is None:
+ item_tax_templates = {}
+
+ if item_rates is None:
+ item_rates = {}
+
+ if isinstance(item_codes, (str,)):
item_codes = json.loads(item_codes)
+ if isinstance(item_rates, (str,)):
+ item_rates = json.loads(item_rates)
+
+ if isinstance(item_tax_templates, (str,)):
+ item_tax_templates = json.loads(item_tax_templates)
+
for item_code in item_codes:
- if not item_code or item_code in out:
+ if not item_code or item_code[1] in out or not item_tax_templates.get(item_code[1]):
continue
- out[item_code] = {}
- item = frappe.get_cached_doc("Item", item_code)
- get_item_tax_template({"company": company, "tax_category": tax_category}, item, out[item_code])
- out[item_code]["item_tax_rate"] = get_item_tax_map(company, out[item_code].get("item_tax_template"), as_json=True)
+
+ out[item_code[1]] = {}
+ item = frappe.get_cached_doc("Item", item_code[0])
+ args = {"company": company, "tax_category": tax_category, "net_rate": item_rates.get(item_code[1])}
+
+ if item_tax_templates:
+ args.update({"item_tax_template": item_tax_templates.get(item_code[1])})
+
+ get_item_tax_template(args, item, out[item_code[1]])
+ out[item_code[1]]["item_tax_rate"] = get_item_tax_map(company, out[item_code[1]].get("item_tax_template"), as_json=True)
return out
@@ -461,9 +477,7 @@ def get_item_tax_template(args, item, out):
}
"""
item_tax_template = args.get("item_tax_template")
-
- if not item_tax_template:
- item_tax_template = _get_item_tax_template(args, item.taxes, out)
+ item_tax_template = _get_item_tax_template(args, item.taxes, out)
if not item_tax_template:
item_group = item.item_group
@@ -472,18 +486,21 @@ def get_item_tax_template(args, item, out):
item_tax_template = _get_item_tax_template(args, item_group_doc.taxes, out)
item_group = item_group_doc.parent_item_group
-def _get_item_tax_template(args, taxes, out={}, for_validate=False):
+def _get_item_tax_template(args, taxes, out=None, for_validate=False):
+ if out is None:
+ out = {}
taxes_with_validity = []
taxes_with_no_validity = []
for tax in taxes:
tax_company = frappe.get_value("Item Tax Template", tax.item_tax_template, 'company')
- if tax.valid_from and tax_company == args['company']:
+ if (tax.valid_from or tax.maximum_net_rate) and tax_company == args['company']:
# In purchase Invoice first preference will be given to supplier invoice date
# if supplier date is not present then posting date
validation_date = args.get('transaction_date') or args.get('bill_date') or args.get('posting_date')
- if getdate(tax.valid_from) <= getdate(validation_date):
+ if getdate(tax.valid_from) <= getdate(validation_date) \
+ and is_within_valid_range(args, tax):
taxes_with_validity.append(tax)
else:
if tax_company == args['company']:
@@ -502,12 +519,26 @@ def _get_item_tax_template(args, taxes, out={}, for_validate=False):
if not taxes_with_validity and (not taxes_with_no_validity):
return None
+ # do not change if already a valid template
+ if args.get('item_tax_template') in {t.item_tax_template for t in taxes}:
+ out["item_tax_template"] = args.get('item_tax_template')
+ return args.get('item_tax_template')
+
for tax in taxes:
if cstr(tax.tax_category) == cstr(args.get("tax_category")):
out["item_tax_template"] = tax.item_tax_template
return tax.item_tax_template
return None
+def is_within_valid_range(args, tax):
+ if not flt(tax.maximum_net_rate):
+ # No range specified, just ignore
+ return True
+ elif flt(tax.minimum_net_rate) <= flt(args.get('net_rate')) <= flt(tax.maximum_net_rate):
+ return True
+
+ return False
+
@frappe.whitelist()
def get_item_tax_map(company, item_tax_template, as_json=True):
item_tax_map = {}
@@ -611,8 +642,12 @@ def get_price_list_rate(args, item_doc, out):
meta = frappe.get_meta(args.parenttype or args.doctype)
if meta.get_field("currency") or args.get('currency'):
- pl_details = get_price_list_currency_and_exchange_rate(args)
- args.update(pl_details)
+ if not args.get("price_list_currency") or not args.get("plc_conversion_rate"):
+ # if currency and plc_conversion_rate exist then
+ # `get_price_list_currency_and_exchange_rate` has already been called
+ pl_details = get_price_list_currency_and_exchange_rate(args)
+ args.update(pl_details)
+
if meta.get_field("currency"):
validate_conversion_rate(args, meta)
@@ -771,10 +806,14 @@ def check_packing_list(price_list_rate_name, desired_qty, item_code):
def validate_conversion_rate(args, meta):
from erpnext.controllers.accounts_controller import validate_conversion_rate
- if (not args.conversion_rate
- and args.currency==frappe.get_cached_value('Company', args.company, "default_currency")):
+ company_currency = frappe.get_cached_value('Company', args.company, "default_currency")
+ if (not args.conversion_rate and args.currency==company_currency):
args.conversion_rate = 1.0
+ if (not args.ignore_conversion_rate and args.conversion_rate == 1 and args.currency!=company_currency):
+ args.conversion_rate = get_exchange_rate(args.currency,
+ company_currency, args.transaction_date, "for_buying") or 1.0
+
# validate currency conversion rate
validate_conversion_rate(args.currency, args.conversion_rate,
meta.get_label("conversion_rate"), args.company)
@@ -922,10 +961,19 @@ def get_projected_qty(item_code, warehouse):
{"item_code": item_code, "warehouse": warehouse}, "projected_qty")}
@frappe.whitelist()
-def get_bin_details(item_code, warehouse):
- return frappe.db.get_value("Bin", {"item_code": item_code, "warehouse": warehouse},
+def get_bin_details(item_code, warehouse, company=None):
+ bin_details = frappe.db.get_value("Bin", {"item_code": item_code, "warehouse": warehouse},
["projected_qty", "actual_qty", "reserved_qty"], as_dict=True, cache=True) \
or {"projected_qty": 0, "actual_qty": 0, "reserved_qty": 0}
+ if company:
+ bin_details['company_total_stock'] = get_company_total_stock(item_code, company)
+ return bin_details
+
+def get_company_total_stock(item_code, company):
+ return frappe.db.sql("""SELECT sum(actual_qty) from
+ (`tabBin` INNER JOIN `tabWarehouse` ON `tabBin`.warehouse = `tabWarehouse`.name)
+ WHERE `tabWarehouse`.company = %s and `tabBin`.item_code = %s""",
+ (company, item_code))[0][0]
@frappe.whitelist()
def get_serial_no_details(item_code, warehouse, stock_qty, serial_no):
@@ -993,6 +1041,8 @@ def apply_price_list(args, as_doc=False):
args = process_args(args)
parent = get_price_list_currency_and_exchange_rate(args)
+ args.update(parent)
+
children = []
if "items" in args:
@@ -1057,7 +1107,7 @@ def get_price_list_currency_and_exchange_rate(args):
return frappe._dict({
"price_list_currency": price_list_currency,
"price_list_uom_dependant": price_list_uom_dependant,
- "plc_conversion_rate": plc_conversion_rate
+ "plc_conversion_rate": plc_conversion_rate or 1
})
@frappe.whitelist()
diff --git a/erpnext/stock/report/batch_wise_balance_history/batch_wise_balance_history.py b/erpnext/stock/report/batch_wise_balance_history/batch_wise_balance_history.py
index 087c12ed2df..01927c2d10f 100644
--- a/erpnext/stock/report/batch_wise_balance_history/batch_wise_balance_history.py
+++ b/erpnext/stock/report/batch_wise_balance_history/batch_wise_balance_history.py
@@ -70,7 +70,7 @@ def get_stock_ledger_entries(filters):
return frappe.db.sql("""
select item_code, batch_no, warehouse, posting_date, sum(actual_qty) as actual_qty
from `tabStock Ledger Entry`
- where docstatus < 2 and ifnull(batch_no, '') != '' %s
+ where is_cancelled = 0 and docstatus < 2 and ifnull(batch_no, '') != '' %s
group by voucher_no, batch_no, item_code, warehouse
order by item_code, warehouse""" %
conditions, as_dict=1)
diff --git a/erpnext/patches/v8_3/__init__.py b/erpnext/stock/report/cogs_by_item_group/__init__.py
similarity index 100%
rename from erpnext/patches/v8_3/__init__.py
rename to erpnext/stock/report/cogs_by_item_group/__init__.py
diff --git a/erpnext/stock/report/cogs_by_item_group/cogs_by_item_group.js b/erpnext/stock/report/cogs_by_item_group/cogs_by_item_group.js
new file mode 100644
index 00000000000..d7c50a66979
--- /dev/null
+++ b/erpnext/stock/report/cogs_by_item_group/cogs_by_item_group.js
@@ -0,0 +1,31 @@
+// Copyright (c) 2016, Frappe Technologies Pvt. Ltd. and contributors
+// For license information, please see license.txt
+/* eslint-disable */
+
+
+frappe.query_reports["COGS By Item Group"] = {
+ filters: [
+ {
+ label: __("Company"),
+ fieldname: "company",
+ fieldtype: "Link",
+ options: "Company",
+ mandatory: true,
+ default: frappe.defaults.get_user_default("Company"),
+ },
+ {
+ label: __("From Date"),
+ fieldname: "from_date",
+ fieldtype: "Date",
+ mandatory: true,
+ default: frappe.datetime.year_start(),
+ },
+ {
+ label: __("To Date"),
+ fieldname: "to_date",
+ fieldtype: "Date",
+ mandatory: true,
+ default: frappe.datetime.get_today(),
+ },
+ ]
+};
diff --git a/erpnext/stock/report/cogs_by_item_group/cogs_by_item_group.json b/erpnext/stock/report/cogs_by_item_group/cogs_by_item_group.json
new file mode 100644
index 00000000000..a14adf8a453
--- /dev/null
+++ b/erpnext/stock/report/cogs_by_item_group/cogs_by_item_group.json
@@ -0,0 +1,32 @@
+{
+ "add_total_row": 0,
+ "columns": [],
+ "creation": "2021-06-02 18:59:19.830928",
+ "disable_prepared_report": 0,
+ "disabled": 0,
+ "docstatus": 0,
+ "doctype": "Report",
+ "filters": [],
+ "idx": 0,
+ "is_standard": "Yes",
+ "modified": "2021-06-02 18:59:55.470621",
+ "modified_by": "Administrator",
+ "module": "Stock",
+ "name": "COGS By Item Group",
+ "owner": "Administrator",
+ "prepared_report": 0,
+ "ref_doctype": "GL Entry",
+ "report_name": "COGS By Item Group",
+ "report_type": "Script Report",
+ "roles": [
+ {
+ "role": "Accounts User"
+ },
+ {
+ "role": "Accounts Manager"
+ },
+ {
+ "role": "Auditor"
+ }
+ ]
+}
\ No newline at end of file
diff --git a/erpnext/stock/report/cogs_by_item_group/cogs_by_item_group.py b/erpnext/stock/report/cogs_by_item_group/cogs_by_item_group.py
new file mode 100644
index 00000000000..9e5e63e37e2
--- /dev/null
+++ b/erpnext/stock/report/cogs_by_item_group/cogs_by_item_group.py
@@ -0,0 +1,188 @@
+# Copyright (c) 2013, Frappe Technologies Pvt. Ltd. and contributors
+# For license information, please see license.txt
+
+from collections import OrderedDict
+import datetime
+from typing import Dict, List, Tuple, Union
+
+import frappe
+from frappe import _
+from frappe.utils import date_diff
+
+from erpnext.accounts.report.general_ledger.general_ledger import get_gl_entries
+
+
+Filters = frappe._dict
+Row = frappe._dict
+Data = List[Row]
+Columns = List[Dict[str, str]]
+DateTime = Union[datetime.date, datetime.datetime]
+FilteredEntries = List[Dict[str, Union[str, float, DateTime, None]]]
+ItemGroupsDict = Dict[Tuple[int, int], Dict[str, Union[str, int]]]
+SVDList = List[frappe._dict]
+
+
+def execute(filters: Filters) -> Tuple[Columns, Data]:
+ update_filters_with_account(filters)
+ validate_filters(filters)
+ columns = get_columns()
+ data = get_data(filters)
+ return columns, data
+
+
+def update_filters_with_account(filters: Filters) -> None:
+ account = frappe.get_value("Company", filters.get("company"), "default_expense_account")
+ filters.update(dict(account=account))
+
+
+def validate_filters(filters: Filters) -> None:
+ if filters.from_date > filters.to_date:
+ frappe.throw(_("From Date must be before To Date"))
+
+
+def get_columns() -> Columns:
+ return [
+ {
+ 'label': 'Item Group',
+ 'fieldname': 'item_group',
+ 'fieldtype': 'Data',
+ 'width': '200'
+ },
+ {
+ 'label': 'COGS Debit',
+ 'fieldname': 'cogs_debit',
+ 'fieldtype': 'Currency',
+ 'width': '200'
+ }
+ ]
+
+
+def get_data(filters: Filters) -> Data:
+ filtered_entries = get_filtered_entries(filters)
+ svd_list = get_stock_value_difference_list(filtered_entries)
+ leveled_dict = get_leveled_dict()
+
+ assign_self_values(leveled_dict, svd_list)
+ assign_agg_values(leveled_dict)
+
+ data = []
+ for item in leveled_dict.items():
+ i = item[1]
+ if i['agg_value'] == 0:
+ continue
+ data.append(get_row(i['name'], i['agg_value'], i['is_group'], i['level']))
+ if i['self_value'] < i['agg_value'] and i['self_value'] > 0:
+ data.append(get_row(i['name'], i['self_value'], 0, i['level'] + 1))
+ return data
+
+
+def get_filtered_entries(filters: Filters) -> FilteredEntries:
+ gl_entries = get_gl_entries(filters, [])
+ filtered_entries = []
+ for entry in gl_entries:
+ posting_date = entry.get('posting_date')
+ from_date = filters.get('from_date')
+ if date_diff(from_date, posting_date) > 0:
+ continue
+ filtered_entries.append(entry)
+ return filtered_entries
+
+
+def get_stock_value_difference_list(filtered_entries: FilteredEntries) -> SVDList:
+ voucher_nos = [fe.get('voucher_no') for fe in filtered_entries]
+ svd_list = frappe.get_list(
+ 'Stock Ledger Entry', fields=['item_code','stock_value_difference'],
+ filters=[('voucher_no', 'in', voucher_nos)]
+ )
+ assign_item_groups_to_svd_list(svd_list)
+ return svd_list
+
+
+def get_leveled_dict() -> OrderedDict:
+ item_groups_dict = get_item_groups_dict()
+ lr_list = sorted(item_groups_dict, key=lambda x : int(x[0]))
+ leveled_dict = OrderedDict()
+ current_level = 0
+ nesting_r = []
+ for l, r in lr_list:
+ while current_level > 0 and nesting_r[-1] < l:
+ nesting_r.pop()
+ current_level -= 1
+
+ leveled_dict[(l,r)] = {
+ 'level' : current_level,
+ 'name' : item_groups_dict[(l,r)]['name'],
+ 'is_group' : item_groups_dict[(l,r)]['is_group']
+ }
+
+ if int(r) - int(l) > 1:
+ current_level += 1
+ nesting_r.append(r)
+
+ update_leveled_dict(leveled_dict)
+ return leveled_dict
+
+
+def assign_self_values(leveled_dict: OrderedDict, svd_list: SVDList) -> None:
+ key_dict = {v['name']:k for k, v in leveled_dict.items()}
+ for item in svd_list:
+ key = key_dict[item.get("item_group")]
+ leveled_dict[key]['self_value'] += -item.get("stock_value_difference")
+
+
+def assign_agg_values(leveled_dict: OrderedDict) -> None:
+ keys = list(leveled_dict.keys())[::-1]
+ prev_level = leveled_dict[keys[-1]]['level']
+ accu = [0]
+ for k in keys[:-1]:
+ curr_level = leveled_dict[k]['level']
+ if curr_level == prev_level:
+ accu[-1] += leveled_dict[k]['self_value']
+ leveled_dict[k]['agg_value'] = leveled_dict[k]['self_value']
+
+ elif curr_level > prev_level:
+ accu.append(leveled_dict[k]['self_value'])
+ leveled_dict[k]['agg_value'] = accu[-1]
+
+ elif curr_level < prev_level:
+ accu[-1] += leveled_dict[k]['self_value']
+ leveled_dict[k]['agg_value'] = accu[-1]
+
+ prev_level = curr_level
+
+ # root node
+ rk = keys[-1]
+ leveled_dict[rk]['agg_value'] = sum(accu) + leveled_dict[rk]['self_value']
+
+
+def get_row(name:str, value:float, is_bold:int, indent:int) -> Row:
+ item_group = name
+ if is_bold:
+ item_group = frappe.bold(item_group)
+ return frappe._dict(item_group=item_group, cogs_debit=value, indent=indent)
+
+
+def assign_item_groups_to_svd_list(svd_list: SVDList) -> None:
+ ig_map = get_item_groups_map(svd_list)
+ for item in svd_list:
+ item.item_group = ig_map[item.get("item_code")]
+
+
+def get_item_groups_map(svd_list: SVDList) -> Dict[str, str]:
+ item_codes = set(i['item_code'] for i in svd_list)
+ ig_list = frappe.get_list(
+ 'Item', fields=['item_code','item_group'],
+ filters=[('item_code', 'in', item_codes)]
+ )
+ return {i['item_code']:i['item_group'] for i in ig_list}
+
+
+def get_item_groups_dict() -> ItemGroupsDict:
+ item_groups_list = frappe.get_all("Item Group", fields=("name", "is_group", "lft", "rgt"))
+ return {(i['lft'],i['rgt']):{'name':i['name'], 'is_group':i['is_group']}
+ for i in item_groups_list}
+
+
+def update_leveled_dict(leveled_dict: OrderedDict) -> None:
+ for k in leveled_dict:
+ leveled_dict[k].update({'self_value':0, 'agg_value':0})
diff --git a/erpnext/patches/v8_5/__init__.py b/erpnext/stock/report/incorrect_balance_qty_after_transaction/__init__.py
similarity index 100%
rename from erpnext/patches/v8_5/__init__.py
rename to erpnext/stock/report/incorrect_balance_qty_after_transaction/__init__.py
diff --git a/erpnext/stock/report/incorrect_balance_qty_after_transaction/incorrect_balance_qty_after_transaction.js b/erpnext/stock/report/incorrect_balance_qty_after_transaction/incorrect_balance_qty_after_transaction.js
new file mode 100644
index 00000000000..bf11277d9c4
--- /dev/null
+++ b/erpnext/stock/report/incorrect_balance_qty_after_transaction/incorrect_balance_qty_after_transaction.js
@@ -0,0 +1,27 @@
+// Copyright (c) 2016, Frappe Technologies Pvt. Ltd. and contributors
+// For license information, please see license.txt
+/* eslint-disable */
+
+frappe.query_reports["Incorrect Balance Qty After Transaction"] = {
+ "filters": [
+ {
+ label: __("Company"),
+ fieldtype: "Link",
+ fieldname: "company",
+ options: "Company",
+ default: frappe.defaults.get_user_default("Company"),
+ reqd: 1
+ },
+ {
+ label: __('Item Code'),
+ fieldtype: 'Link',
+ fieldname: 'item_code',
+ options: 'Item'
+ },
+ {
+ label: __('Warehouse'),
+ fieldtype: 'Link',
+ fieldname: 'warehouse'
+ }
+ ]
+};
diff --git a/erpnext/stock/report/incorrect_balance_qty_after_transaction/incorrect_balance_qty_after_transaction.json b/erpnext/stock/report/incorrect_balance_qty_after_transaction/incorrect_balance_qty_after_transaction.json
new file mode 100644
index 00000000000..a5815bcca49
--- /dev/null
+++ b/erpnext/stock/report/incorrect_balance_qty_after_transaction/incorrect_balance_qty_after_transaction.json
@@ -0,0 +1,32 @@
+{
+ "add_total_row": 0,
+ "columns": [],
+ "creation": "2021-05-12 16:47:58.717853",
+ "disable_prepared_report": 0,
+ "disabled": 0,
+ "docstatus": 0,
+ "doctype": "Report",
+ "filters": [],
+ "idx": 0,
+ "is_standard": "Yes",
+ "modified": "2021-05-12 16:48:28.347575",
+ "modified_by": "Administrator",
+ "module": "Stock",
+ "name": "Incorrect Balance Qty After Transaction",
+ "owner": "Administrator",
+ "prepared_report": 0,
+ "ref_doctype": "Stock Ledger Entry",
+ "report_name": "Incorrect Balance Qty After Transaction",
+ "report_type": "Script Report",
+ "roles": [
+ {
+ "role": "Stock User"
+ },
+ {
+ "role": "Stock Manager"
+ },
+ {
+ "role": "Purchase User"
+ }
+ ]
+}
\ No newline at end of file
diff --git a/erpnext/stock/report/incorrect_balance_qty_after_transaction/incorrect_balance_qty_after_transaction.py b/erpnext/stock/report/incorrect_balance_qty_after_transaction/incorrect_balance_qty_after_transaction.py
new file mode 100644
index 00000000000..cf174c93682
--- /dev/null
+++ b/erpnext/stock/report/incorrect_balance_qty_after_transaction/incorrect_balance_qty_after_transaction.py
@@ -0,0 +1,111 @@
+# Copyright (c) 2013, Frappe Technologies Pvt. Ltd. and contributors
+# For license information, please see license.txt
+
+import frappe
+from frappe import _
+from six import iteritems
+from frappe.utils import flt
+
+def execute(filters=None):
+ columns, data = [], []
+ columns = get_columns()
+ data = get_data(filters)
+ return columns, data
+
+def get_data(filters):
+ data = get_stock_ledger_entries(filters)
+ itewise_balance_qty = {}
+
+ for row in data:
+ key = (row.item_code, row.warehouse)
+ itewise_balance_qty.setdefault(key, []).append(row)
+
+ res = validate_data(itewise_balance_qty)
+ return res
+
+def validate_data(itewise_balance_qty):
+ res = []
+ for key, data in iteritems(itewise_balance_qty):
+ row = get_incorrect_data(data)
+ if row:
+ res.append(row)
+ res.append({})
+
+ return res
+
+def get_incorrect_data(data):
+ balance_qty = 0.0
+ for row in data:
+ balance_qty += row.actual_qty
+ if row.voucher_type == "Stock Reconciliation" and not row.batch_no:
+ balance_qty = flt(row.qty_after_transaction)
+
+ row.expected_balance_qty = balance_qty
+ if abs(flt(row.expected_balance_qty) - flt(row.qty_after_transaction)) > 0.5:
+ row.differnce = abs(flt(row.expected_balance_qty) - flt(row.qty_after_transaction))
+ return row
+
+def get_stock_ledger_entries(report_filters):
+ filters = {}
+ fields = ['name', 'voucher_type', 'voucher_no', 'item_code', 'actual_qty',
+ 'posting_date', 'posting_time', 'company', 'warehouse', 'qty_after_transaction', 'batch_no']
+
+ for field in ['warehouse', 'item_code', 'company']:
+ if report_filters.get(field):
+ filters[field] = report_filters.get(field)
+
+ return frappe.get_all('Stock Ledger Entry', fields = fields, filters = filters,
+ order_by = 'timestamp(posting_date, posting_time) asc, creation asc')
+
+def get_columns():
+ return [{
+ 'label': _('Id'),
+ 'fieldtype': 'Link',
+ 'fieldname': 'name',
+ 'options': 'Stock Ledger Entry',
+ 'width': 120
+ }, {
+ 'label': _('Posting Date'),
+ 'fieldtype': 'Date',
+ 'fieldname': 'posting_date',
+ 'width': 110
+ }, {
+ 'label': _('Voucher Type'),
+ 'fieldtype': 'Link',
+ 'fieldname': 'voucher_type',
+ 'options': 'DocType',
+ 'width': 120
+ }, {
+ 'label': _('Voucher No'),
+ 'fieldtype': 'Dynamic Link',
+ 'fieldname': 'voucher_no',
+ 'options': 'voucher_type',
+ 'width': 120
+ }, {
+ 'label': _('Item Code'),
+ 'fieldtype': 'Link',
+ 'fieldname': 'item_code',
+ 'options': 'Item',
+ 'width': 120
+ }, {
+ 'label': _('Warehouse'),
+ 'fieldtype': 'Link',
+ 'fieldname': 'warehouse',
+ 'options': 'Warehouse',
+ 'width': 120
+ }, {
+ 'label': _('Expected Balance Qty'),
+ 'fieldtype': 'Float',
+ 'fieldname': 'expected_balance_qty',
+ 'width': 170
+ }, {
+ 'label': _('Actual Balance Qty'),
+ 'fieldtype': 'Float',
+ 'fieldname': 'qty_after_transaction',
+ 'width': 150
+ }, {
+ 'label': _('Difference'),
+ 'fieldtype': 'Float',
+ 'fieldname': 'differnce',
+ 'width': 110
+ }]
\ No newline at end of file
diff --git a/erpnext/patches/v8_6/__init__.py b/erpnext/stock/report/incorrect_serial_no_valuation/__init__.py
similarity index 100%
rename from erpnext/patches/v8_6/__init__.py
rename to erpnext/stock/report/incorrect_serial_no_valuation/__init__.py
diff --git a/erpnext/stock/report/incorrect_serial_no_valuation/incorrect_serial_no_valuation.js b/erpnext/stock/report/incorrect_serial_no_valuation/incorrect_serial_no_valuation.js
new file mode 100644
index 00000000000..c62d48081c2
--- /dev/null
+++ b/erpnext/stock/report/incorrect_serial_no_valuation/incorrect_serial_no_valuation.js
@@ -0,0 +1,35 @@
+// Copyright (c) 2016, Frappe Technologies Pvt. Ltd. and contributors
+// For license information, please see license.txt
+/* eslint-disable */
+
+frappe.query_reports["Incorrect Serial No Valuation"] = {
+ "filters": [
+ {
+ label: __('Item Code'),
+ fieldtype: 'Link',
+ fieldname: 'item_code',
+ options: 'Item',
+ get_query: function() {
+ return {
+ filters: {
+ 'has_serial_no': 1
+ }
+ }
+ }
+ },
+ {
+ label: __('From Date'),
+ fieldtype: 'Date',
+ fieldname: 'from_date',
+ reqd: 1,
+ default: frappe.defaults.get_user_default("year_start_date")
+ },
+ {
+ label: __('To Date'),
+ fieldtype: 'Date',
+ fieldname: 'to_date',
+ reqd: 1,
+ default: frappe.defaults.get_user_default("year_end_date")
+ }
+ ]
+};
diff --git a/erpnext/stock/report/incorrect_serial_no_valuation/incorrect_serial_no_valuation.json b/erpnext/stock/report/incorrect_serial_no_valuation/incorrect_serial_no_valuation.json
new file mode 100644
index 00000000000..cc384a5bd03
--- /dev/null
+++ b/erpnext/stock/report/incorrect_serial_no_valuation/incorrect_serial_no_valuation.json
@@ -0,0 +1,36 @@
+{
+ "add_total_row": 0,
+ "columns": [],
+ "creation": "2021-05-13 13:07:00.767845",
+ "disable_prepared_report": 0,
+ "disabled": 0,
+ "docstatus": 0,
+ "doctype": "Report",
+ "filters": [],
+ "idx": 0,
+ "is_standard": "Yes",
+ "json": "{}",
+ "modified": "2021-05-13 13:07:00.767845",
+ "modified_by": "Administrator",
+ "module": "Stock",
+ "name": "Incorrect Serial No Valuation",
+ "owner": "Administrator",
+ "prepared_report": 0,
+ "ref_doctype": "Stock Ledger Entry",
+ "report_name": "Incorrect Serial No Valuation",
+ "report_type": "Script Report",
+ "roles": [
+ {
+ "role": "Stock User"
+ },
+ {
+ "role": "Accounts Manager"
+ },
+ {
+ "role": "Accounts User"
+ },
+ {
+ "role": "Stock Manager"
+ }
+ ]
+}
\ No newline at end of file
diff --git a/erpnext/stock/report/incorrect_serial_no_valuation/incorrect_serial_no_valuation.py b/erpnext/stock/report/incorrect_serial_no_valuation/incorrect_serial_no_valuation.py
new file mode 100644
index 00000000000..e54cf4c66c7
--- /dev/null
+++ b/erpnext/stock/report/incorrect_serial_no_valuation/incorrect_serial_no_valuation.py
@@ -0,0 +1,148 @@
+# Copyright (c) 2013, Frappe Technologies Pvt. Ltd. and contributors
+# For license information, please see license.txt
+
+import frappe
+import copy
+from frappe import _
+from six import iteritems
+from erpnext.stock.doctype.serial_no.serial_no import get_serial_nos
+
+def execute(filters=None):
+ columns, data = [], []
+ columns = get_columns()
+ data = get_data(filters)
+ return columns, data
+
+def get_data(filters):
+ data = get_stock_ledger_entries(filters)
+ serial_nos_data = prepare_serial_nos(data)
+ data = get_incorrect_serial_nos(serial_nos_data)
+
+ return data
+
+def prepare_serial_nos(data):
+ serial_no_wise_data = {}
+ for row in data:
+ if not row.serial_nos:
+ continue
+
+ for serial_no in get_serial_nos(row.serial_nos):
+ sle = copy.deepcopy(row)
+ sle.serial_no = serial_no
+ sle.qty = 1 if sle.actual_qty > 0 else -1
+ sle.valuation_rate = sle.valuation_rate if sle.actual_qty > 0 else sle.valuation_rate * -1
+ serial_no_wise_data.setdefault(serial_no, []).append(sle)
+
+ return serial_no_wise_data
+
+def get_incorrect_serial_nos(serial_nos_data):
+ result = []
+
+ total_value = frappe._dict({'qty': 0, 'valuation_rate': 0, 'serial_no': frappe.bold(_('Balance'))})
+
+ for serial_no, data in iteritems(serial_nos_data):
+ total_dict = frappe._dict({'qty': 0, 'valuation_rate': 0, 'serial_no': frappe.bold(_('Total'))})
+
+ if check_incorrect_serial_data(data, total_dict):
+ result.extend(data)
+
+ total_value.qty += total_dict.qty
+ total_value.valuation_rate += total_dict.valuation_rate
+
+ result.append(total_dict)
+ result.append({})
+
+ result.append(total_value)
+
+ return result
+
+def check_incorrect_serial_data(data, total_dict):
+ incorrect_data = False
+ for row in data:
+ total_dict.qty += row.qty
+ total_dict.valuation_rate += row.valuation_rate
+
+ if ((total_dict.qty == 0 and abs(total_dict.valuation_rate) > 0) or total_dict.qty < 0):
+ incorrect_data = True
+
+ return incorrect_data
+
+def get_stock_ledger_entries(report_filters):
+ fields = ['name', 'voucher_type', 'voucher_no', 'item_code', 'serial_no as serial_nos', 'actual_qty',
+ 'posting_date', 'posting_time', 'company', 'warehouse', '(stock_value_difference / actual_qty) as valuation_rate']
+
+ filters = {'serial_no': ("is", "set")}
+
+ if report_filters.get('item_code'):
+ filters['item_code'] = report_filters.get('item_code')
+
+ if report_filters.get('from_date') and report_filters.get('to_date'):
+ filters['posting_date'] = ('between', [report_filters.get('from_date'), report_filters.get('to_date')])
+
+ return frappe.get_all('Stock Ledger Entry', fields = fields, filters = filters,
+ order_by = 'timestamp(posting_date, posting_time) asc, creation asc')
+
+def get_columns():
+ return [{
+ 'label': _('Company'),
+ 'fieldtype': 'Link',
+ 'fieldname': 'company',
+ 'options': 'Company',
+ 'width': 120
+ }, {
+ 'label': _('Id'),
+ 'fieldtype': 'Link',
+ 'fieldname': 'name',
+ 'options': 'Stock Ledger Entry',
+ 'width': 120
+ }, {
+ 'label': _('Posting Date'),
+ 'fieldtype': 'Date',
+ 'fieldname': 'posting_date',
+ 'width': 90
+ }, {
+ 'label': _('Posting Time'),
+ 'fieldtype': 'Time',
+ 'fieldname': 'posting_time',
+ 'width': 90
+ }, {
+ 'label': _('Voucher Type'),
+ 'fieldtype': 'Link',
+ 'fieldname': 'voucher_type',
+ 'options': 'DocType',
+ 'width': 100
+ }, {
+ 'label': _('Voucher No'),
+ 'fieldtype': 'Dynamic Link',
+ 'fieldname': 'voucher_no',
+ 'options': 'voucher_type',
+ 'width': 110
+ }, {
+ 'label': _('Item Code'),
+ 'fieldtype': 'Link',
+ 'fieldname': 'item_code',
+ 'options': 'Item',
+ 'width': 120
+ }, {
+ 'label': _('Warehouse'),
+ 'fieldtype': 'Link',
+ 'fieldname': 'warehouse',
+ 'options': 'Warehouse',
+ 'width': 120
+ }, {
+ 'label': _('Serial No'),
+ 'fieldtype': 'Link',
+ 'fieldname': 'serial_no',
+ 'options': 'Serial No',
+ 'width': 100
+ }, {
+ 'label': _('Qty'),
+ 'fieldtype': 'Float',
+ 'fieldname': 'qty',
+ 'width': 80
+ }, {
+ 'label': _('Valuation Rate (In / Out)'),
+ 'fieldtype': 'Currency',
+ 'fieldname': 'valuation_rate',
+ 'width': 110
+ }]
\ No newline at end of file
diff --git a/erpnext/patches/v8_7/__init__.py b/erpnext/stock/report/incorrect_stock_value_report/__init__.py
similarity index 100%
rename from erpnext/patches/v8_7/__init__.py
rename to erpnext/stock/report/incorrect_stock_value_report/__init__.py
diff --git a/erpnext/stock/report/incorrect_stock_value_report/incorrect_stock_value_report.js b/erpnext/stock/report/incorrect_stock_value_report/incorrect_stock_value_report.js
new file mode 100644
index 00000000000..ff424807e3e
--- /dev/null
+++ b/erpnext/stock/report/incorrect_stock_value_report/incorrect_stock_value_report.js
@@ -0,0 +1,36 @@
+// Copyright (c) 2016, Frappe Technologies Pvt. Ltd. and contributors
+// For license information, please see license.txt
+/* eslint-disable */
+
+frappe.query_reports["Incorrect Stock Value Report"] = {
+ "filters": [
+ {
+ "label": __("Company"),
+ "fieldname": "company",
+ "fieldtype": "Link",
+ "options": "Company",
+ "reqd": 1,
+ "default": frappe.defaults.get_user_default("Company")
+ },
+ {
+ "label": __("Account"),
+ "fieldname": "account",
+ "fieldtype": "Link",
+ "options": "Account",
+ get_query: function() {
+ var company = frappe.query_report.get_filter_value('company');
+ return {
+ filters: {
+ "account_type": "Stock",
+ "company": company
+ }
+ }
+ }
+ },
+ {
+ "label": __("From Date"),
+ "fieldname": "from_date",
+ "fieldtype": "Date"
+ }
+ ]
+};
diff --git a/erpnext/stock/report/incorrect_stock_value_report/incorrect_stock_value_report.json b/erpnext/stock/report/incorrect_stock_value_report/incorrect_stock_value_report.json
new file mode 100644
index 00000000000..a7e9f203f7b
--- /dev/null
+++ b/erpnext/stock/report/incorrect_stock_value_report/incorrect_stock_value_report.json
@@ -0,0 +1,29 @@
+{
+ "add_total_row": 0,
+ "columns": [],
+ "creation": "2021-06-22 15:35:05.148177",
+ "disable_prepared_report": 0,
+ "disabled": 0,
+ "docstatus": 0,
+ "doctype": "Report",
+ "filters": [],
+ "idx": 0,
+ "is_standard": "Yes",
+ "modified": "2021-06-22 15:35:05.148177",
+ "modified_by": "Administrator",
+ "module": "Stock",
+ "name": "Incorrect Stock Value Report",
+ "owner": "Administrator",
+ "prepared_report": 0,
+ "ref_doctype": "Stock Ledger Entry",
+ "report_name": "Incorrect Stock Value Report",
+ "report_type": "Script Report",
+ "roles": [
+ {
+ "role": "Stock User"
+ },
+ {
+ "role": "Accounts Manager"
+ }
+ ]
+}
\ No newline at end of file
diff --git a/erpnext/stock/report/incorrect_stock_value_report/incorrect_stock_value_report.py b/erpnext/stock/report/incorrect_stock_value_report/incorrect_stock_value_report.py
new file mode 100644
index 00000000000..a7243878eb8
--- /dev/null
+++ b/erpnext/stock/report/incorrect_stock_value_report/incorrect_stock_value_report.py
@@ -0,0 +1,141 @@
+# Copyright (c) 2013, Frappe Technologies Pvt. Ltd. and contributors
+# For license information, please see license.txt
+
+from __future__ import unicode_literals
+import frappe
+import erpnext
+from frappe import _
+from six import iteritems
+from frappe.utils import add_days, today, getdate
+from erpnext.stock.utils import get_stock_value_on
+from erpnext.accounts.utils import get_stock_and_account_balance
+
+def execute(filters=None):
+ if not erpnext.is_perpetual_inventory_enabled(filters.company):
+ frappe.throw(_("Perpetual inventory required for the company {0} to view this report.")
+ .format(filters.company))
+
+ data = get_data(filters)
+ columns = get_columns(filters)
+
+ return columns, data
+
+def get_unsync_date(filters):
+ date = filters.from_date
+ if not date:
+ date = frappe.db.sql(""" SELECT min(posting_date) from `tabStock Ledger Entry`""")
+ date = date[0][0]
+
+ if not date:
+ return
+
+ while getdate(date) < getdate(today()):
+ account_bal, stock_bal, warehouse_list = get_stock_and_account_balance(posting_date=date,
+ company=filters.company, account = filters.account)
+
+ if abs(account_bal - stock_bal) > 0.1:
+ return date
+
+ date = add_days(date, 1)
+
+def get_data(report_filters):
+ from_date = get_unsync_date(report_filters)
+
+ if not from_date:
+ return []
+
+ result = []
+
+ voucher_wise_dict = {}
+ data = frappe.db.sql('''
+ SELECT
+ name, posting_date, posting_time, voucher_type, voucher_no,
+ stock_value_difference, stock_value, warehouse, item_code
+ FROM
+ `tabStock Ledger Entry`
+ WHERE
+ posting_date
+ = %s and company = %s
+ and is_cancelled = 0
+ ORDER BY timestamp(posting_date, posting_time) asc, creation asc
+ ''', (from_date, report_filters.company), as_dict=1)
+
+ for d in data:
+ voucher_wise_dict.setdefault((d.item_code, d.warehouse), []).append(d)
+
+ closing_date = add_days(from_date, -1)
+ for key, stock_data in iteritems(voucher_wise_dict):
+ prev_stock_value = get_stock_value_on(posting_date = closing_date, item_code=key[0], warehouse =key[1])
+ for data in stock_data:
+ expected_stock_value = prev_stock_value + data.stock_value_difference
+ if abs(data.stock_value - expected_stock_value) > 0.1:
+ data.difference_value = abs(data.stock_value - expected_stock_value)
+ data.expected_stock_value = expected_stock_value
+ result.append(data)
+
+ return result
+
+def get_columns(filters):
+ return [
+ {
+ "label": _("Stock Ledger ID"),
+ "fieldname": "name",
+ "fieldtype": "Link",
+ "options": "Stock Ledger Entry",
+ "width": "80"
+ },
+ {
+ "label": _("Posting Date"),
+ "fieldname": "posting_date",
+ "fieldtype": "Date"
+ },
+ {
+ "label": _("Posting Time"),
+ "fieldname": "posting_time",
+ "fieldtype": "Time"
+ },
+ {
+ "label": _("Voucher Type"),
+ "fieldname": "voucher_type",
+ "width": "110"
+ },
+ {
+ "label": _("Voucher No"),
+ "fieldname": "voucher_no",
+ "fieldtype": "Dynamic Link",
+ "options": "voucher_type",
+ "width": "110"
+ },
+ {
+ "label": _("Item Code"),
+ "fieldname": "item_code",
+ "fieldtype": "Link",
+ "options": "Item",
+ "width": "110"
+ },
+ {
+ "label": _("Warehouse"),
+ "fieldname": "warehouse",
+ "fieldtype": "Link",
+ "options": "Warehouse",
+ "width": "110"
+ },
+ {
+ "label": _("Expected Stock Value"),
+ "fieldname": "expected_stock_value",
+ "fieldtype": "Currency",
+ "width": "150"
+ },
+ {
+ "label": _("Stock Value"),
+ "fieldname": "stock_value",
+ "fieldtype": "Currency",
+ "width": "120"
+ },
+ {
+ "label": _("Difference Value"),
+ "fieldname": "difference_value",
+ "fieldtype": "Currency",
+ "width": "150"
+ }
+ ]
\ No newline at end of file
diff --git a/erpnext/stock/report/item_price_stock/item_price_stock.py b/erpnext/stock/report/item_price_stock/item_price_stock.py
index 5296211fae8..db7498bb215 100644
--- a/erpnext/stock/report/item_price_stock/item_price_stock.py
+++ b/erpnext/stock/report/item_price_stock/item_price_stock.py
@@ -89,7 +89,7 @@ def get_item_price_qty_data(filters):
{conditions}"""
.format(conditions=conditions), filters, as_dict=1)
- price_list_names = list(set([item.price_list_name for item in item_results]))
+ price_list_names = list(set(item.price_list_name for item in item_results))
buying_price_map = get_price_map(price_list_names, buying=1)
selling_price_map = get_price_map(price_list_names, selling=1)
diff --git a/erpnext/stock/report/item_variant_details/item_variant_details.py b/erpnext/stock/report/item_variant_details/item_variant_details.py
index e8449cc33ec..d8563d79271 100644
--- a/erpnext/stock/report/item_variant_details/item_variant_details.py
+++ b/erpnext/stock/report/item_variant_details/item_variant_details.py
@@ -14,47 +14,58 @@ def get_data(item):
if not item:
return []
item_dicts = []
- variants = None
- variant_results = frappe.db.sql("""select name from `tabItem`
- where variant_of = %s""", item, as_dict=1)
+ variant_results = frappe.db.get_all(
+ "Item",
+ fields=["name"],
+ filters={
+ "variant_of": ["=", item],
+ "disabled": 0
+ }
+ )
+
if not variant_results:
- frappe.msgprint(_("There isn't any item variant for the selected item"))
+ frappe.msgprint(_("There aren't any item variants for the selected item"))
return []
else:
- variants = ", ".join([frappe.db.escape(variant['name']) for variant in variant_results])
+ variant_list = [variant['name'] for variant in variant_results]
- order_count_map = get_open_sales_orders_map(variants)
- stock_details_map = get_stock_details_map(variants)
- buying_price_map = get_buying_price_map(variants)
- selling_price_map = get_selling_price_map(variants)
- attr_val_map = get_attribute_values_map(variants)
+ order_count_map = get_open_sales_orders_count(variant_list)
+ stock_details_map = get_stock_details_map(variant_list)
+ buying_price_map = get_buying_price_map(variant_list)
+ selling_price_map = get_selling_price_map(variant_list)
+ attr_val_map = get_attribute_values_map(variant_list)
- attribute_list = [d[0] for d in frappe.db.sql("""select attribute
- from `tabItem Variant Attribute`
- where parent in ({variants}) group by attribute""".format(variants=variants))]
+ attributes = frappe.db.get_all(
+ "Item Variant Attribute",
+ fields=["attribute"],
+ filters={
+ "parent": ["in", variant_list]
+ },
+ group_by="attribute"
+ )
+ attribute_list = [row.get("attribute") for row in attributes]
# Prepare dicts
variant_dicts = [{"variant_name": d['name']} for d in variant_results]
for item_dict in variant_dicts:
- name = item_dict["variant_name"]
+ name = item_dict.get("variant_name")
- for d in attribute_list:
- attr_dict = attr_val_map[name]
- if attr_dict and attr_dict.get(d):
- item_dict[d] = attr_val_map[name][d]
+ for attribute in attribute_list:
+ attr_dict = attr_val_map.get(name)
+ if attr_dict and attr_dict.get(attribute):
+ item_dict[frappe.scrub(attribute)] = attr_val_map.get(name).get(attribute)
- item_dict["Open Orders"] = order_count_map.get(name) or 0
+ item_dict["open_orders"] = order_count_map.get(name) or 0
if stock_details_map.get(name):
- item_dict["Inventory"] = stock_details_map.get(name)["Inventory"] or 0
- item_dict["In Production"] = stock_details_map.get(name)["In Production"] or 0
- item_dict["Available Selling"] = stock_details_map.get(name)["Available Selling"] or 0
+ item_dict["current_stock"] = stock_details_map.get(name)["Inventory"] or 0
+ item_dict["in_production"] = stock_details_map.get(name)["In Production"] or 0
else:
- item_dict["Inventory"] = item_dict["In Production"] = item_dict["Available Selling"] = 0
+ item_dict["current_stock"] = item_dict["in_production"] = 0
- item_dict["Avg. Buying Price List Rate"] = buying_price_map.get(name) or 0
- item_dict["Avg. Selling Price List Rate"] = selling_price_map.get(name) or 0
+ item_dict["avg_buying_price_list_rate"] = buying_price_map.get(name) or 0
+ item_dict["avg_selling_price_list_rate"] = selling_price_map.get(name) or 0
item_dicts.append(item_dict)
@@ -71,117 +82,158 @@ def get_columns(item):
item_doc = frappe.get_doc("Item", item)
- for d in item_doc.attributes:
- columns.append(d.attribute + ":Data:100")
+ for entry in item_doc.attributes:
+ columns.append({
+ "fieldname": frappe.scrub(entry.attribute),
+ "label": entry.attribute,
+ "fieldtype": "Data",
+ "width": 100
+ })
- columns += [_("Avg. Buying Price List Rate") + ":Currency:110", _("Avg. Selling Price List Rate") + ":Currency:110",
- _("Inventory") + ":Float:100", _("In Production") + ":Float:100",
- _("Open Orders") + ":Float:100", _("Available Selling") + ":Float:100"
+ additional_columns = [
+ {
+ "fieldname": "avg_buying_price_list_rate",
+ "label": _("Avg. Buying Price List Rate"),
+ "fieldtype": "Currency",
+ "width": 150
+ },
+ {
+ "fieldname": "avg_selling_price_list_rate",
+ "label": _("Avg. Selling Price List Rate"),
+ "fieldtype": "Currency",
+ "width": 150
+ },
+ {
+ "fieldname": "current_stock",
+ "label": _("Current Stock"),
+ "fieldtype": "Float",
+ "width": 120
+ },
+ {
+ "fieldname": "in_production",
+ "label": _("In Production"),
+ "fieldtype": "Float",
+ "width": 150
+ },
+ {
+ "fieldname": "open_orders",
+ "label": _("Open Sales Orders"),
+ "fieldtype": "Float",
+ "width": 150
+ }
]
+ columns.extend(additional_columns)
return columns
-def get_open_sales_orders_map(variants):
- open_sales_orders = frappe.db.sql("""
- select
- count(*) as count,
- item_code
- from
- `tabSales Order Item`
- where
- docstatus = 1 and
- qty > ifnull(delivered_qty, 0) and
- item_code in ({variants})
- group by
- item_code
- """.format(variants=variants), as_dict=1)
+def get_open_sales_orders_count(variants_list):
+ open_sales_orders = frappe.db.get_list(
+ "Sales Order",
+ fields=[
+ "name",
+ "`tabSales Order Item`.item_code"
+ ],
+ filters=[
+ ["Sales Order", "docstatus", "=", 1],
+ ["Sales Order Item", "item_code", "in", variants_list]
+ ],
+ distinct=1
+ )
order_count_map = {}
- for d in open_sales_orders:
- order_count_map[d["item_code"]] = d["count"]
+ for row in open_sales_orders:
+ item_code = row.get("item_code")
+ if order_count_map.get(item_code) is None:
+ order_count_map[item_code] = 1
+ else:
+ order_count_map[item_code] += 1
return order_count_map
-def get_stock_details_map(variants):
- stock_details = frappe.db.sql("""
- select
- sum(planned_qty) as planned_qty,
- sum(actual_qty) as actual_qty,
- sum(projected_qty) as projected_qty,
- item_code
- from
- `tabBin`
- where
- item_code in ({variants})
- group by
- item_code
- """.format(variants=variants), as_dict=1)
+def get_stock_details_map(variant_list):
+ stock_details = frappe.db.get_all(
+ "Bin",
+ fields=[
+ "sum(planned_qty) as planned_qty",
+ "sum(actual_qty) as actual_qty",
+ "sum(projected_qty) as projected_qty",
+ "item_code",
+ ],
+ filters={
+ "item_code": ["in", variant_list]
+ },
+ group_by="item_code"
+ )
stock_details_map = {}
- for d in stock_details:
- name = d["item_code"]
+ for row in stock_details:
+ name = row.get("item_code")
stock_details_map[name] = {
- "Inventory" :d["actual_qty"],
- "In Production" :d["planned_qty"],
- "Available Selling" :d["projected_qty"]
+ "Inventory": row.get("actual_qty"),
+ "In Production": row.get("planned_qty")
}
return stock_details_map
-def get_buying_price_map(variants):
- buying = frappe.db.sql("""
- select
- avg(price_list_rate) as avg_rate,
- item_code
- from
- `tabItem Price`
- where
- item_code in ({variants}) and buying=1
- group by
- item_code
- """.format(variants=variants), as_dict=1)
+def get_buying_price_map(variant_list):
+ buying = frappe.db.get_all(
+ "Item Price",
+ fields=[
+ "avg(price_list_rate) as avg_rate",
+ "item_code",
+ ],
+ filters={
+ "item_code": ["in", variant_list],
+ "buying": 1
+ },
+ group_by="item_code"
+ )
buying_price_map = {}
- for d in buying:
- buying_price_map[d["item_code"]] = d["avg_rate"]
+ for row in buying:
+ buying_price_map[row.get("item_code")] = row.get("avg_rate")
return buying_price_map
-def get_selling_price_map(variants):
- selling = frappe.db.sql("""
- select
- avg(price_list_rate) as avg_rate,
- item_code
- from
- `tabItem Price`
- where
- item_code in ({variants}) and selling=1
- group by
- item_code
- """.format(variants=variants), as_dict=1)
+def get_selling_price_map(variant_list):
+ selling = frappe.db.get_all(
+ "Item Price",
+ fields=[
+ "avg(price_list_rate) as avg_rate",
+ "item_code",
+ ],
+ filters={
+ "item_code": ["in", variant_list],
+ "selling": 1
+ },
+ group_by="item_code"
+ )
selling_price_map = {}
- for d in selling:
- selling_price_map[d["item_code"]] = d["avg_rate"]
+ for row in selling:
+ selling_price_map[row.get("item_code")] = row.get("avg_rate")
return selling_price_map
-def get_attribute_values_map(variants):
- list_attr = frappe.db.sql("""
- select
- attribute, attribute_value, parent
- from
- `tabItem Variant Attribute`
- where
- parent in ({variants})
- """.format(variants=variants), as_dict=1)
+def get_attribute_values_map(variant_list):
+ attribute_list = frappe.db.get_all(
+ "Item Variant Attribute",
+ fields=[
+ "attribute",
+ "attribute_value",
+ "parent"
+ ],
+ filters={
+ "parent": ["in", variant_list]
+ }
+ )
attr_val_map = {}
- for d in list_attr:
- name = d["parent"]
+ for row in attribute_list:
+ name = row.get("parent")
if not attr_val_map.get(name):
attr_val_map[name] = {}
- attr_val_map[name][d["attribute"]] = d["attribute_value"]
+ attr_val_map[name][row.get("attribute")] = row.get("attribute_value")
return attr_val_map
diff --git a/erpnext/stock/report/itemwise_recommended_reorder_level/itemwise_recommended_reorder_level.py b/erpnext/stock/report/itemwise_recommended_reorder_level/itemwise_recommended_reorder_level.py
index 5df3fa8067b..2e13aa0b040 100644
--- a/erpnext/stock/report/itemwise_recommended_reorder_level/itemwise_recommended_reorder_level.py
+++ b/erpnext/stock/report/itemwise_recommended_reorder_level/itemwise_recommended_reorder_level.py
@@ -55,19 +55,31 @@ def get_item_info(filters):
def get_consumed_items(condition):
+ purpose_to_exclude = [
+ "Material Transfer for Manufacture",
+ "Material Transfer",
+ "Send to Subcontractor"
+ ]
+
+ condition += """
+ and (
+ purpose is NULL
+ or purpose not in ({})
+ )
+ """.format(', '.join(f"'{p}'" for p in purpose_to_exclude))
+ condition = condition.replace("posting_date", "sle.posting_date")
+
consumed_items = frappe.db.sql("""
select item_code, abs(sum(actual_qty)) as consumed_qty
- from `tabStock Ledger Entry`
- where actual_qty < 0
+ from `tabStock Ledger Entry` as sle left join `tabStock Entry` as se
+ on sle.voucher_no = se.name
+ where
+ actual_qty < 0
and voucher_type not in ('Delivery Note', 'Sales Invoice')
%s
- group by item_code
- """ % condition, as_dict=1)
-
- consumed_items_map = {}
- for item in consumed_items:
- consumed_items_map.setdefault(item.item_code, item.consumed_qty)
+ group by item_code""" % condition, as_dict=1)
+ consumed_items_map = {item.item_code : item.consumed_qty for item in consumed_items}
return consumed_items_map
def get_delivered_items(condition):
diff --git a/erpnext/stock/report/product_bundle_balance/product_bundle_balance.py b/erpnext/stock/report/product_bundle_balance/product_bundle_balance.py
index 276e42ee433..8fffbccab3c 100644
--- a/erpnext/stock/report/product_bundle_balance/product_bundle_balance.py
+++ b/erpnext/stock/report/product_bundle_balance/product_bundle_balance.py
@@ -141,7 +141,7 @@ def get_stock_ledger_entries(filters, items):
return []
item_conditions_sql = ' and sle.item_code in ({})' \
- .format(', '.join([frappe.db.escape(i) for i in items]))
+ .format(', '.join(frappe.db.escape(i) for i in items))
conditions = get_sle_conditions(filters)
diff --git a/erpnext/patches/v8_8/__init__.py b/erpnext/stock/report/serial_no_ledger/__init__.py
similarity index 100%
rename from erpnext/patches/v8_8/__init__.py
rename to erpnext/stock/report/serial_no_ledger/__init__.py
diff --git a/erpnext/stock/report/serial_no_ledger/serial_no_ledger.js b/erpnext/stock/report/serial_no_ledger/serial_no_ledger.js
new file mode 100644
index 00000000000..616312e3118
--- /dev/null
+++ b/erpnext/stock/report/serial_no_ledger/serial_no_ledger.js
@@ -0,0 +1,52 @@
+// Copyright (c) 2016, Frappe Technologies Pvt. Ltd. and contributors
+// For license information, please see license.txt
+/* eslint-disable */
+
+frappe.query_reports["Serial No Ledger"] = {
+ "filters": [
+ {
+ 'label': __('Item Code'),
+ 'fieldtype': 'Link',
+ 'fieldname': 'item_code',
+ 'reqd': 1,
+ 'options': 'Item',
+ get_query: function() {
+ return {
+ filters: {
+ 'has_serial_no': 1
+ }
+ }
+ }
+ },
+ {
+ 'label': __('Serial No'),
+ 'fieldtype': 'Link',
+ 'fieldname': 'serial_no',
+ 'options': 'Serial No',
+ 'reqd': 1
+ },
+ {
+ 'label': __('Warehouse'),
+ 'fieldtype': 'Link',
+ 'fieldname': 'warehouse',
+ 'options': 'Warehouse',
+ get_query: function() {
+ let company = frappe.query_report.get_filter_value('company');
+
+ if (company) {
+ return {
+ filters: {
+ 'company': company
+ }
+ }
+ }
+ }
+ },
+ {
+ 'label': __('As On Date'),
+ 'fieldtype': 'Date',
+ 'fieldname': 'posting_date',
+ 'default': frappe.datetime.get_today()
+ },
+ ]
+};
diff --git a/erpnext/stock/report/serial_no_ledger/serial_no_ledger.json b/erpnext/stock/report/serial_no_ledger/serial_no_ledger.json
new file mode 100644
index 00000000000..e20e74c78b7
--- /dev/null
+++ b/erpnext/stock/report/serial_no_ledger/serial_no_ledger.json
@@ -0,0 +1,33 @@
+{
+ "add_total_row": 0,
+ "columns": [],
+ "creation": "2021-04-20 13:32:41.523219",
+ "disable_prepared_report": 0,
+ "disabled": 0,
+ "docstatus": 0,
+ "doctype": "Report",
+ "filters": [],
+ "idx": 0,
+ "is_standard": "Yes",
+ "json": "{}",
+ "modified": "2021-04-20 13:33:19.015829",
+ "modified_by": "Administrator",
+ "module": "Stock",
+ "name": "Serial No Ledger",
+ "owner": "Administrator",
+ "prepared_report": 0,
+ "ref_doctype": "Stock Ledger Entry",
+ "report_name": "Serial No Ledger",
+ "report_type": "Script Report",
+ "roles": [
+ {
+ "role": "Stock User"
+ },
+ {
+ "role": "Purchase User"
+ },
+ {
+ "role": "Sales User"
+ }
+ ]
+}
\ No newline at end of file
diff --git a/erpnext/stock/report/serial_no_ledger/serial_no_ledger.py b/erpnext/stock/report/serial_no_ledger/serial_no_ledger.py
new file mode 100644
index 00000000000..c3339fd341e
--- /dev/null
+++ b/erpnext/stock/report/serial_no_ledger/serial_no_ledger.py
@@ -0,0 +1,53 @@
+# Copyright (c) 2013, Frappe Technologies Pvt. Ltd. and contributors
+# For license information, please see license.txt
+
+from __future__ import unicode_literals
+from frappe import _
+from erpnext.stock.stock_ledger import get_stock_ledger_entries
+from erpnext.stock.doctype.serial_no.serial_no import get_serial_nos
+
+def execute(filters=None):
+ columns = get_columns(filters)
+ data = get_data(filters)
+ return columns, data
+
+def get_columns(filters):
+ columns = [{
+ 'label': _('Posting Date'),
+ 'fieldtype': 'Date',
+ 'fieldname': 'posting_date'
+ }, {
+ 'label': _('Posting Time'),
+ 'fieldtype': 'Time',
+ 'fieldname': 'posting_time'
+ }, {
+ 'label': _('Voucher Type'),
+ 'fieldtype': 'Link',
+ 'fieldname': 'voucher_type',
+ 'options': 'DocType',
+ 'width': 220
+ }, {
+ 'label': _('Voucher No'),
+ 'fieldtype': 'Dynamic Link',
+ 'fieldname': 'voucher_no',
+ 'options': 'voucher_type',
+ 'width': 220
+ }, {
+ 'label': _('Company'),
+ 'fieldtype': 'Link',
+ 'fieldname': 'company',
+ 'options': 'Company',
+ 'width': 220
+ }, {
+ 'label': _('Warehouse'),
+ 'fieldtype': 'Link',
+ 'fieldname': 'warehouse',
+ 'options': 'Warehouse',
+ 'width': 220
+ }]
+
+ return columns
+
+def get_data(filters):
+ return get_stock_ledger_entries(filters, '<=', order="asc") or []
+
diff --git a/erpnext/stock/report/stock_ageing/stock_ageing.py b/erpnext/stock/report/stock_ageing/stock_ageing.py
index ff603fcfb3a..623dc2ffd97 100644
--- a/erpnext/stock/report/stock_ageing/stock_ageing.py
+++ b/erpnext/stock/report/stock_ageing/stock_ageing.py
@@ -49,7 +49,7 @@ def get_average_age(fifo_queue, to_date):
for batch in fifo_queue:
batch_age = date_diff(to_date, batch[1])
- if type(batch[0]) in ['int', 'float']:
+ if isinstance(batch[0], (int, float)):
age_qty += batch_age * batch[0]
total_qty += batch[0]
else:
@@ -302,4 +302,4 @@ def add_column(range_columns, label, fieldname, fieldtype='Float', width=140):
fieldname=fieldname,
fieldtype=fieldtype,
width=width
- ))
\ No newline at end of file
+ ))
diff --git a/erpnext/stock/report/stock_balance/stock_balance.py b/erpnext/stock/report/stock_balance/stock_balance.py
index 6dfede45906..b6a80631892 100644
--- a/erpnext/stock/report/stock_balance/stock_balance.py
+++ b/erpnext/stock/report/stock_balance/stock_balance.py
@@ -157,7 +157,7 @@ def get_stock_ledger_entries(filters, items):
item_conditions_sql = ''
if items:
item_conditions_sql = ' and sle.item_code in ({})'\
- .format(', '.join([frappe.db.escape(i, percent=False) for i in items]))
+ .format(', '.join(frappe.db.escape(i, percent=False) for i in items))
conditions = get_conditions(filters)
@@ -165,7 +165,7 @@ def get_stock_ledger_entries(filters, items):
select
sle.item_code, warehouse, sle.posting_date, sle.actual_qty, sle.valuation_rate,
sle.company, sle.voucher_type, sle.qty_after_transaction, sle.stock_value_difference,
- sle.item_code as name, sle.voucher_no, sle.stock_value
+ sle.item_code as name, sle.voucher_no, sle.stock_value, sle.batch_no
from
`tabStock Ledger Entry` sle force index (posting_sort_index)
where sle.docstatus < 2 %s %s
@@ -193,7 +193,7 @@ def get_item_warehouse_map(filters, sle):
qty_dict = iwb_map[(d.company, d.item_code, d.warehouse)]
- if d.voucher_type == "Stock Reconciliation":
+ if d.voucher_type == "Stock Reconciliation" and not d.batch_no:
qty_diff = flt(d.qty_after_transaction) - flt(qty_dict.bal_qty)
else:
qty_diff = flt(d.actual_qty)
@@ -253,7 +253,7 @@ def get_items(filters):
def get_item_details(items, sle, filters):
item_details = {}
if not items:
- items = list(set([d.item_code for d in sle]))
+ items = list(set(d.item_code for d in sle))
if not items:
return item_details
@@ -291,7 +291,7 @@ def get_item_reorder_details(items):
select parent, warehouse, warehouse_reorder_qty, warehouse_reorder_level
from `tabItem Reorder`
where parent in ({0})
- """.format(', '.join([frappe.db.escape(i, percent=False) for i in items])), as_dict=1)
+ """.format(', '.join(frappe.db.escape(i, percent=False) for i in items)), as_dict=1)
return dict((d.parent + d.warehouse, d) for d in item_reorder_details)
diff --git a/erpnext/stock/report/stock_ledger/stock_ledger.py b/erpnext/stock/report/stock_ledger/stock_ledger.py
index 36996e96745..8909f217f49 100644
--- a/erpnext/stock/report/stock_ledger/stock_ledger.py
+++ b/erpnext/stock/report/stock_ledger/stock_ledger.py
@@ -115,7 +115,7 @@ def get_stock_ledger_entries(filters, items):
item_conditions_sql = ''
if items:
item_conditions_sql = 'and sle.item_code in ({})'\
- .format(', '.join([frappe.db.escape(i) for i in items]))
+ .format(', '.join(frappe.db.escape(i) for i in items))
sl_entries = frappe.db.sql("""
SELECT
@@ -169,7 +169,7 @@ def get_items(filters):
def get_item_details(items, sl_entries, include_uom):
item_details = {}
if not items:
- items = list(set([d.item_code for d in sl_entries]))
+ items = list(set(d.item_code for d in sl_entries))
if not items:
return item_details
diff --git a/erpnext/stock/report/stock_projected_qty/stock_projected_qty.js b/erpnext/stock/report/stock_projected_qty/stock_projected_qty.js
index babc6dc9602..cb109f8050d 100644
--- a/erpnext/stock/report/stock_projected_qty/stock_projected_qty.js
+++ b/erpnext/stock/report/stock_projected_qty/stock_projected_qty.js
@@ -14,7 +14,14 @@ frappe.query_reports["Stock Projected Qty"] = {
"fieldname":"warehouse",
"label": __("Warehouse"),
"fieldtype": "Link",
- "options": "Warehouse"
+ "options": "Warehouse",
+ "get_query": () => {
+ return {
+ filters: {
+ company: frappe.query_report.get_filter_value('company')
+ }
+ }
+ }
},
{
"fieldname":"item_code",
diff --git a/erpnext/stock/report/stock_projected_qty/stock_projected_qty.py b/erpnext/stock/report/stock_projected_qty/stock_projected_qty.py
index 1183e41d041..808d2791709 100644
--- a/erpnext/stock/report/stock_projected_qty/stock_projected_qty.py
+++ b/erpnext/stock/report/stock_projected_qty/stock_projected_qty.py
@@ -6,6 +6,7 @@ import frappe
from frappe import _
from frappe.utils import flt, today
from erpnext.stock.utils import update_included_uom_in_report, is_reposting_item_valuation_in_progress
+from erpnext.accounts.doctype.pos_invoice.pos_invoice import get_pos_reserved_qty
def execute(filters=None):
is_reposting_item_valuation_in_progress()
@@ -49,9 +50,13 @@ def execute(filters=None):
if (re_order_level or re_order_qty) and re_order_level > bin.projected_qty:
shortage_qty = re_order_level - flt(bin.projected_qty)
+ reserved_qty_for_pos = get_pos_reserved_qty(bin.item_code, bin.warehouse)
+ if reserved_qty_for_pos:
+ bin.projected_qty -= reserved_qty_for_pos
+
data.append([item.name, item.item_name, item.description, item.item_group, item.brand, bin.warehouse,
item.stock_uom, bin.actual_qty, bin.planned_qty, bin.indented_qty, bin.ordered_qty,
- bin.reserved_qty, bin.reserved_qty_for_production, bin.reserved_qty_for_sub_contract,
+ bin.reserved_qty, bin.reserved_qty_for_production, bin.reserved_qty_for_sub_contract, reserved_qty_for_pos,
bin.projected_qty, re_order_level, re_order_qty, shortage_qty])
if include_uom:
@@ -74,9 +79,11 @@ def get_columns():
{"label": _("Requested Qty"), "fieldname": "indented_qty", "fieldtype": "Float", "width": 110, "convertible": "qty"},
{"label": _("Ordered Qty"), "fieldname": "ordered_qty", "fieldtype": "Float", "width": 100, "convertible": "qty"},
{"label": _("Reserved Qty"), "fieldname": "reserved_qty", "fieldtype": "Float", "width": 100, "convertible": "qty"},
- {"label": _("Reserved Qty for Production"), "fieldname": "reserved_qty_for_production", "fieldtype": "Float",
+ {"label": _("Reserved for Production"), "fieldname": "reserved_qty_for_production", "fieldtype": "Float",
"width": 100, "convertible": "qty"},
- {"label": _("Reserved for sub contracting"), "fieldname": "reserved_qty_for_sub_contract", "fieldtype": "Float",
+ {"label": _("Reserved for Sub Contracting"), "fieldname": "reserved_qty_for_sub_contract", "fieldtype": "Float",
+ "width": 100, "convertible": "qty"},
+ {"label": _("Reserved for POS Transactions"), "fieldname": "reserved_qty_for_pos", "fieldtype": "Float",
"width": 100, "convertible": "qty"},
{"label": _("Projected Qty"), "fieldname": "projected_qty", "fieldtype": "Float", "width": 100, "convertible": "qty"},
{"label": _("Reorder Level"), "fieldname": "re_order_level", "fieldtype": "Float", "width": 100, "convertible": "qty"},
diff --git a/erpnext/stock/report/supplier_wise_sales_analytics/supplier_wise_sales_analytics.py b/erpnext/stock/report/supplier_wise_sales_analytics/supplier_wise_sales_analytics.py
index 5873a7a3008..4108a575542 100644
--- a/erpnext/stock/report/supplier_wise_sales_analytics/supplier_wise_sales_analytics.py
+++ b/erpnext/stock/report/supplier_wise_sales_analytics/supplier_wise_sales_analytics.py
@@ -69,7 +69,7 @@ def get_consumed_details(filters):
i.stock_uom, sle.actual_qty, sle.stock_value_difference,
sle.voucher_no, sle.voucher_type
from `tabStock Ledger Entry` sle, `tabItem` i
- where sle.item_code=i.name and sle.actual_qty < 0 %s""" % conditions, values, as_dict=1):
+ where sle.is_cancelled = 0 and sle.item_code=i.name and sle.actual_qty < 0 %s""" % conditions, values, as_dict=1):
consumed_details.setdefault(d.item_code, []).append(d)
return consumed_details
diff --git a/erpnext/stock/report/total_stock_summary/total_stock_summary.py b/erpnext/stock/report/total_stock_summary/total_stock_summary.py
index ed523939232..59c253c425b 100644
--- a/erpnext/stock/report/total_stock_summary/total_stock_summary.py
+++ b/erpnext/stock/report/total_stock_summary/total_stock_summary.py
@@ -51,7 +51,7 @@ def get_total_stock(filters):
INNER JOIN `tabWarehouse` warehouse
ON warehouse.name = ledger.warehouse
WHERE
- actual_qty != 0 %s""" % (columns, conditions))
+ ledger.actual_qty != 0 %s""" % (columns, conditions))
def validate_filters(filters):
if filters.get("group_by") == 'Company' and \
diff --git a/erpnext/stock/stock_balance.py b/erpnext/stock/stock_balance.py
index 8ba1f1ca5c7..8917bfeae4f 100644
--- a/erpnext/stock/stock_balance.py
+++ b/erpnext/stock/stock_balance.py
@@ -194,9 +194,6 @@ def set_stock_balance_as_per_serial_no(item_code=None, posting_date=None, postin
serial_nos = frappe.db.sql("""select count(name) from `tabSerial No`
where item_code=%s and warehouse=%s and docstatus < 2""", (d[0], d[1]))
- if serial_nos and flt(serial_nos[0][0]) != flt(d[2]):
- print(d[0], d[1], d[2], serial_nos[0][0])
-
sle = frappe.db.sql("""select valuation_rate, company from `tabStock Ledger Entry`
where item_code = %s and warehouse = %s and is_cancelled = 0
order by posting_date desc limit 1""", (d[0], d[1]))
@@ -230,7 +227,7 @@ def set_stock_balance_as_per_serial_no(item_code=None, posting_date=None, postin
})
update_bin(args)
-
+
create_repost_item_valuation_entry({
"item_code": d[0],
"warehouse": d[1],
diff --git a/erpnext/stock/stock_ledger.py b/erpnext/stock/stock_ledger.py
index 121c51cf6a6..c15d1eda7dc 100644
--- a/erpnext/stock/stock_ledger.py
+++ b/erpnext/stock/stock_ledger.py
@@ -2,22 +2,28 @@
# License: GNU General Public License v3. See license.txt
from __future__ import unicode_literals
-import frappe, erpnext
+import frappe
+import erpnext
+import copy
from frappe import _
-from frappe.utils import cint, flt, cstr, now, now_datetime
+from frappe.utils import cint, flt, cstr, now, get_link_to_form, getdate
from frappe.model.meta import get_field_precision
from erpnext.stock.utils import get_valuation_method, get_incoming_outgoing_rate_for_cancel
from erpnext.stock.utils import get_bin
import json
from six import iteritems
+
# future reposting
class NegativeStockError(frappe.ValidationError): pass
+class SerialNoExistsInFutureTransaction(frappe.ValidationError):
+ pass
_exceptions = frappe.local('stockledger_exceptions')
# _exceptions = []
def make_sl_entries(sl_entries, allow_negative_stock=False, via_landed_cost_voucher=False):
+ from erpnext.controllers.stock_controller import future_sle_exists
if sl_entries:
from erpnext.stock.utils import update_bin
@@ -26,7 +32,13 @@ def make_sl_entries(sl_entries, allow_negative_stock=False, via_landed_cost_vouc
validate_cancellation(sl_entries)
set_as_cancel(sl_entries[0].get('voucher_type'), sl_entries[0].get('voucher_no'))
+ args = get_args_for_future_sle(sl_entries[0])
+ future_sle_exists(args, sl_entries)
+
for sle in sl_entries:
+ if sle.serial_no:
+ validate_serial_no(sle)
+
if cancel:
sle['actual_qty'] = -flt(sle.get('actual_qty'))
@@ -44,8 +56,45 @@ def make_sl_entries(sl_entries, allow_negative_stock=False, via_landed_cost_vouc
sle_doc = make_entry(sle, allow_negative_stock, via_landed_cost_voucher)
args = sle_doc.as_dict()
+
+ if sle.get("voucher_type") == "Stock Reconciliation":
+ # preserve previous_qty_after_transaction for qty reposting
+ args.previous_qty_after_transaction = sle.get("previous_qty_after_transaction")
+
update_bin(args, allow_negative_stock, via_landed_cost_voucher)
+def get_args_for_future_sle(row):
+ return frappe._dict({
+ 'voucher_type': row.get('voucher_type'),
+ 'voucher_no': row.get('voucher_no'),
+ 'posting_date': row.get('posting_date'),
+ 'posting_time': row.get('posting_time')
+ })
+
+def validate_serial_no(sle):
+ from erpnext.stock.doctype.serial_no.serial_no import get_serial_nos
+ for sn in get_serial_nos(sle.serial_no):
+ args = copy.deepcopy(sle)
+ args.serial_no = sn
+ args.warehouse = ''
+
+ vouchers = []
+ for row in get_stock_ledger_entries(args, '>'):
+ voucher_type = frappe.bold(row.voucher_type)
+ voucher_no = frappe.bold(get_link_to_form(row.voucher_type, row.voucher_no))
+ vouchers.append(f'{voucher_type} {voucher_no}')
+
+ if vouchers:
+ serial_no = frappe.bold(sn)
+ msg = (f'''The serial no {serial_no} has been used in the future transactions so you need to cancel them first.
+ The list of the transactions are as below.''' + '
')
+
+ msg += '
'.join(vouchers)
+ msg += '
'
+
+ title = 'Cannot Submit' if not sle.get('is_cancelled') else 'Cannot Cancel'
+ frappe.throw(_(msg), title=_(title), exc=SerialNoExistsInFutureTransaction)
+
def validate_cancellation(args):
if args[0].get("is_cancelled"):
repost_entry = frappe.db.get_value("Repost Item Valuation", {
@@ -82,7 +131,13 @@ def repost_future_sle(args=None, voucher_type=None, voucher_no=None, allow_negat
if not args and voucher_type and voucher_no:
args = get_args_for_voucher(voucher_type, voucher_no)
- distinct_item_warehouses = [(d.item_code, d.warehouse) for d in args]
+ distinct_item_warehouses = {}
+ for i, d in enumerate(args):
+ distinct_item_warehouses.setdefault((d.item_code, d.warehouse), frappe._dict({
+ "reposting_status": False,
+ "sle": d,
+ "args_idx": i
+ }))
i = 0
while i < len(args):
@@ -91,13 +146,21 @@ def repost_future_sle(args=None, voucher_type=None, voucher_no=None, allow_negat
"warehouse": args[i].warehouse,
"posting_date": args[i].posting_date,
"posting_time": args[i].posting_time,
- "creation": args[i].get("creation")
+ "creation": args[i].get("creation"),
+ "distinct_item_warehouses": distinct_item_warehouses
}, allow_negative_stock=allow_negative_stock, via_landed_cost_voucher=via_landed_cost_voucher)
- for item_wh, new_sle in iteritems(obj.new_items):
- if item_wh not in distinct_item_warehouses:
- args.append(new_sle)
+ distinct_item_warehouses[(args[i].item_code, args[i].warehouse)].reposting_status = True
+ if obj.new_items_found:
+ for item_wh, data in iteritems(distinct_item_warehouses):
+ if ('args_idx' not in data and not data.reposting_status) or (data.sle_changed and data.reposting_status):
+ data.args_idx = len(args)
+ args.append(data.sle)
+ elif data.sle_changed and not data.reposting_status:
+ args[data.args_idx] = data.sle
+
+ data.sle_changed = False
i += 1
def get_args_for_voucher(voucher_type, voucher_no):
@@ -138,11 +201,12 @@ class update_entries_after(object):
self.company = frappe.get_cached_value("Warehouse", self.args.warehouse, "company")
self.get_precision()
self.valuation_method = get_valuation_method(self.item_code)
- self.new_items = {}
+
+ self.new_items_found = False
+ self.distinct_item_warehouses = args.get("distinct_item_warehouses", frappe._dict())
self.data = frappe._dict()
self.initialize_previous_data(self.args)
-
self.build()
def get_precision(self):
@@ -172,7 +236,7 @@ class update_entries_after(object):
"""
self.data.setdefault(args.warehouse, frappe._dict())
warehouse_dict = self.data[args.warehouse]
- previous_sle = self.get_previous_sle_of_current_voucher(args)
+ previous_sle = get_previous_sle_of_current_voucher(args)
warehouse_dict.previous_sle = previous_sle
for key in ("qty_after_transaction", "valuation_rate", "stock_value"):
@@ -184,28 +248,6 @@ class update_entries_after(object):
"stock_value_difference": 0.0
})
- def get_previous_sle_of_current_voucher(self, args):
- """get stock ledger entries filtered by specific posting datetime conditions"""
-
- args['time_format'] = '%H:%i:%s'
- if not args.get("posting_date"):
- args["posting_date"] = "1900-01-01"
- if not args.get("posting_time"):
- args["posting_time"] = "00:00"
-
- sle = frappe.db.sql("""
- select *, timestamp(posting_date, posting_time) as "timestamp"
- from `tabStock Ledger Entry`
- where item_code = %(item_code)s
- and warehouse = %(warehouse)s
- and is_cancelled = 0
- and timestamp(posting_date, time_format(posting_time, %(time_format)s)) < timestamp(%(posting_date)s, time_format(%(posting_time)s, %(time_format)s))
- order by timestamp(posting_date, posting_time) desc, creation desc
- limit 1""", args, as_dict=1)
-
- return sle[0] if sle else frappe._dict()
-
-
def build(self):
from erpnext.controllers.stock_controller import future_sle_exists
@@ -270,11 +312,29 @@ class update_entries_after(object):
elif dependant_sle.item_code == self.item_code and dependant_sle.warehouse == self.args.warehouse:
return entries_to_fix
elif dependant_sle.item_code != self.item_code:
- if (dependant_sle.item_code, dependant_sle.warehouse) not in self.new_items:
- self.new_items[(dependant_sle.item_code, dependant_sle.warehouse)] = dependant_sle
+ self.update_distinct_item_warehouses(dependant_sle)
return entries_to_fix
elif dependant_sle.item_code == self.item_code and dependant_sle.warehouse in self.data:
return entries_to_fix
+ else:
+ return self.append_future_sle_for_dependant(dependant_sle, entries_to_fix)
+
+ def update_distinct_item_warehouses(self, dependant_sle):
+ key = (dependant_sle.item_code, dependant_sle.warehouse)
+ val = frappe._dict({
+ "sle": dependant_sle
+ })
+ if key not in self.distinct_item_warehouses:
+ self.distinct_item_warehouses[key] = val
+ self.new_items_found = True
+ else:
+ existing_sle_posting_date = self.distinct_item_warehouses[key].get("sle", {}).get("posting_date")
+ if getdate(dependant_sle.posting_date) < getdate(existing_sle_posting_date):
+ val.sle_changed = True
+ self.distinct_item_warehouses[key] = val
+ self.new_items_found = True
+
+ def append_future_sle_for_dependant(self, dependant_sle, entries_to_fix):
self.initialize_previous_data(dependant_sle)
args = self.data[dependant_sle.warehouse].previous_sle \
@@ -367,12 +427,14 @@ class update_entries_after(object):
rate = 0
# Material Transfer, Repack, Manufacturing
if sle.voucher_type == "Stock Entry":
+ self.recalculate_amounts_in_stock_entry(sle.voucher_no)
rate = frappe.db.get_value("Stock Entry Detail", sle.voucher_detail_no, "valuation_rate")
# Sales and Purchase Return
elif sle.voucher_type in ("Purchase Receipt", "Purchase Invoice", "Delivery Note", "Sales Invoice"):
if frappe.get_cached_value(sle.voucher_type, sle.voucher_no, "is_return"):
from erpnext.controllers.sales_and_purchase_return import get_rate_for_return # don't move this import to top
- rate = get_rate_for_return(sle.voucher_type, sle.voucher_no, sle.item_code, voucher_detail_no=sle.voucher_detail_no)
+ rate = get_rate_for_return(sle.voucher_type, sle.voucher_no, sle.item_code,
+ voucher_detail_no=sle.voucher_detail_no, sle = sle)
else:
if sle.voucher_type in ("Purchase Receipt", "Purchase Invoice"):
rate_field = "valuation_rate"
@@ -415,7 +477,11 @@ class update_entries_after(object):
frappe.db.set_value("Stock Entry Detail", sle.voucher_detail_no, "basic_rate", outgoing_rate)
# Update outgoing item's rate, recalculate FG Item's rate and total incoming/outgoing amount
- stock_entry = frappe.get_doc("Stock Entry", sle.voucher_no)
+ if not sle.dependant_sle_voucher_detail_no:
+ self.recalculate_amounts_in_stock_entry(sle.voucher_no)
+
+ def recalculate_amounts_in_stock_entry(self, voucher_no):
+ stock_entry = frappe.get_doc("Stock Entry", voucher_no, for_update=True)
stock_entry.calculate_rate_and_amount(reset_outgoing_rate=False, raise_error_if_no_rate=False)
stock_entry.db_update()
for d in stock_entry.items:
@@ -439,7 +505,7 @@ class update_entries_after(object):
frappe.db.set_value("Purchase Receipt Item Supplied", sle.voucher_detail_no, "rate", outgoing_rate)
# Recalculate subcontracted item's rate in case of subcontracted purchase receipt/invoice
- if frappe.db.get_value(sle.voucher_type, sle.voucher_no, "is_subcontracted"):
+ if frappe.get_cached_value(sle.voucher_type, sle.voucher_no, "is_subcontracted") == 'Yes':
doc = frappe.get_doc(sle.voucher_type, sle.voucher_no)
doc.update_valuation_rate(reset_outgoing_rate=False)
for d in (doc.items + doc.supplied_items):
@@ -488,7 +554,7 @@ class update_entries_after(object):
fields=["purchase_rate", "name", "company"],
filters = {'name': ('in', serial_nos)})
- incoming_values = sum([flt(d.purchase_rate) for d in all_serial_nos if d.company==sle.company])
+ incoming_values = sum(flt(d.purchase_rate) for d in all_serial_nos if d.company==sle.company)
# Get rate for serial nos which has been transferred to other company
invalid_serial_nos = [d.name for d in all_serial_nos if d.company!=sle.company]
@@ -591,7 +657,7 @@ class update_entries_after(object):
break
# If no entry found with outgoing rate, collapse stack
- if index == None:
+ if index is None: # nosemgrep
new_stock_value = sum((d[0]*d[1] for d in self.wh_data.stock_queue)) - qty_to_pop*outgoing_rate
new_stock_qty = sum((d[0] for d in self.wh_data.stock_queue)) - qty_to_pop
self.wh_data.stock_queue = [[new_stock_qty, new_stock_value/new_stock_qty if new_stock_qty > 0 else outgoing_rate]]
@@ -603,7 +669,7 @@ class update_entries_after(object):
batch = self.wh_data.stock_queue[index]
if qty_to_pop >= batch[0]:
# consume current batch
- qty_to_pop = qty_to_pop - batch[0]
+ qty_to_pop = _round_off_if_near_zero(qty_to_pop - batch[0])
self.wh_data.stock_queue.pop(index)
if not self.wh_data.stock_queue and qty_to_pop:
# stock finished, qty still remains to be withdrawn
@@ -617,8 +683,8 @@ class update_entries_after(object):
batch[0] = batch[0] - qty_to_pop
qty_to_pop = 0
- stock_value = sum((flt(batch[0]) * flt(batch[1]) for batch in self.wh_data.stock_queue))
- stock_qty = sum((flt(batch[0]) for batch in self.wh_data.stock_queue))
+ stock_value = _round_off_if_near_zero(sum((flt(batch[0]) * flt(batch[1]) for batch in self.wh_data.stock_queue)))
+ stock_qty = _round_off_if_near_zero(sum((flt(batch[0]) for batch in self.wh_data.stock_queue)))
if stock_qty:
self.wh_data.valuation_rate = stock_value / flt(stock_qty)
@@ -689,6 +755,35 @@ class update_entries_after(object):
bin_doc.flags.via_stock_ledger_entry = True
bin_doc.save(ignore_permissions=True)
+
+def get_previous_sle_of_current_voucher(args, exclude_current_voucher=False):
+ """get stock ledger entries filtered by specific posting datetime conditions"""
+
+ args['time_format'] = '%H:%i:%s'
+ if not args.get("posting_date"):
+ args["posting_date"] = "1900-01-01"
+ if not args.get("posting_time"):
+ args["posting_time"] = "00:00"
+
+ voucher_condition = ""
+ if exclude_current_voucher:
+ voucher_no = args.get("voucher_no")
+ voucher_condition = f"and voucher_no != '{voucher_no}'"
+
+ sle = frappe.db.sql("""
+ select *, timestamp(posting_date, posting_time) as "timestamp"
+ from `tabStock Ledger Entry`
+ where item_code = %(item_code)s
+ and warehouse = %(warehouse)s
+ and is_cancelled = 0
+ {voucher_condition}
+ and timestamp(posting_date, time_format(posting_time, %(time_format)s)) < timestamp(%(posting_date)s, time_format(%(posting_time)s, %(time_format)s))
+ order by timestamp(posting_date, posting_time) desc, creation desc
+ limit 1
+ for update""".format(voucher_condition=voucher_condition), args, as_dict=1)
+
+ return sle[0] if sle else frappe._dict()
+
def get_previous_sle(args, for_update=False):
"""
get the last sle on or before the current time-bucket,
@@ -717,7 +812,17 @@ def get_stock_ledger_entries(previous_sle, operator=None,
conditions += " and " + previous_sle.get("warehouse_condition")
if check_serial_no and previous_sle.get("serial_no"):
- conditions += " and serial_no like {}".format(frappe.db.escape('%{0}%'.format(previous_sle.get("serial_no"))))
+ # conditions += " and serial_no like {}".format(frappe.db.escape('%{0}%'.format(previous_sle.get("serial_no"))))
+ serial_no = previous_sle.get("serial_no")
+ conditions += (""" and
+ (
+ serial_no = {0}
+ or serial_no like {1}
+ or serial_no like {2}
+ or serial_no like {3}
+ )
+ """).format(frappe.db.escape(serial_no), frappe.db.escape('{}\n%'.format(serial_no)),
+ frappe.db.escape('%\n{}'.format(serial_no)), frappe.db.escape('%\n{}\n%'.format(serial_no)))
if not previous_sle.get("posting_date"):
previous_sle["posting_date"] = "1900-01-01"
@@ -792,12 +897,12 @@ def get_valuation_rate(item_code, warehouse, voucher_type, voucher_no,
if not allow_zero_rate and not valuation_rate and raise_error_if_no_rate \
and cint(erpnext.is_perpetual_inventory_enabled(company)):
frappe.local.message_log = []
- form_link = frappe.utils.get_link_to_form("Item", item_code)
+ form_link = get_link_to_form("Item", item_code)
message = _("Valuation Rate for the Item {0}, is required to do accounting entries for {1} {2}.").format(form_link, voucher_type, voucher_no)
- message += "
" + _(" Here are the options to proceed:")
+ message += "
" + _("Here are the options to proceed:")
solutions = "
" + _("If the item is transacting as a Zero Valuation Rate item in this entry, please enable 'Allow Zero Valuation Rate' in the {0} Item table.").format(voucher_type) + "
"
- solutions += "
" + _("If not, you can Cancel / Submit this entry ") + _("{0}").format(frappe.bold("after")) + _(" performing either one below:") + "
"
+ solutions += "
" + _("If not, you can Cancel / Submit this entry") + " {0} ".format(frappe.bold("after")) + _("performing either one below:") + "
"
sub_solutions = "
" + _("Create an incoming stock transaction for the Item.") + "
"
sub_solutions += "
" + _("Mention Valuation Rate in the Item master.") + "
"
msg = message + solutions + sub_solutions + ""
@@ -807,9 +912,24 @@ def get_valuation_rate(item_code, warehouse, voucher_type, voucher_no,
return valuation_rate
def update_qty_in_future_sle(args, allow_negative_stock=None):
+ """Recalculate Qty after Transaction in future SLEs based on current SLE."""
+ datetime_limit_condition = ""
+ qty_shift = args.actual_qty
+
+ # find difference/shift in qty caused by stock reconciliation
+ if args.voucher_type == "Stock Reconciliation":
+ qty_shift = get_stock_reco_qty_shift(args)
+
+ # find the next nearest stock reco so that we only recalculate SLEs till that point
+ next_stock_reco_detail = get_next_stock_reco(args)
+ if next_stock_reco_detail:
+ detail = next_stock_reco_detail[0]
+ # add condition to update SLEs before this date & time
+ datetime_limit_condition = get_datetime_limit_condition(detail)
+
frappe.db.sql("""
update `tabStock Ledger Entry`
- set qty_after_transaction = qty_after_transaction + {qty}
+ set qty_after_transaction = qty_after_transaction + {qty_shift}
where
item_code = %(item_code)s
and warehouse = %(warehouse)s
@@ -821,15 +941,70 @@ def update_qty_in_future_sle(args, allow_negative_stock=None):
and creation > %(creation)s
)
)
- """.format(qty=args.actual_qty), args)
+ {datetime_limit_condition}
+ """.format(qty_shift=qty_shift, datetime_limit_condition=datetime_limit_condition), args)
validate_negative_qty_in_future_sle(args, allow_negative_stock)
+def get_stock_reco_qty_shift(args):
+ stock_reco_qty_shift = 0
+ if args.get("is_cancelled"):
+ if args.get("previous_qty_after_transaction"):
+ # get qty (balance) that was set at submission
+ last_balance = args.get("previous_qty_after_transaction")
+ stock_reco_qty_shift = flt(args.qty_after_transaction) - flt(last_balance)
+ else:
+ stock_reco_qty_shift = flt(args.actual_qty)
+ else:
+ # reco is being submitted
+ last_balance = get_previous_sle_of_current_voucher(args,
+ exclude_current_voucher=True).get("qty_after_transaction")
+
+ if last_balance is not None:
+ stock_reco_qty_shift = flt(args.qty_after_transaction) - flt(last_balance)
+ else:
+ stock_reco_qty_shift = args.qty_after_transaction
+
+ return stock_reco_qty_shift
+
+def get_next_stock_reco(args):
+ """Returns next nearest stock reconciliaton's details."""
+
+ return frappe.db.sql("""
+ select
+ name, posting_date, posting_time, creation, voucher_no
+ from
+ `tabStock Ledger Entry`
+ where
+ item_code = %(item_code)s
+ and warehouse = %(warehouse)s
+ and voucher_type = 'Stock Reconciliation'
+ and voucher_no != %(voucher_no)s
+ and is_cancelled = 0
+ and (timestamp(posting_date, posting_time) > timestamp(%(posting_date)s, %(posting_time)s)
+ or (
+ timestamp(posting_date, posting_time) = timestamp(%(posting_date)s, %(posting_time)s)
+ and creation > %(creation)s
+ )
+ )
+ limit 1
+ """, args, as_dict=1)
+
+def get_datetime_limit_condition(detail):
+ return f"""
+ and
+ (timestamp(posting_date, posting_time) < timestamp('{detail.posting_date}', '{detail.posting_time}')
+ or (
+ timestamp(posting_date, posting_time) = timestamp('{detail.posting_date}', '{detail.posting_time}')
+ and creation < '{detail.creation}'
+ )
+ )"""
+
def validate_negative_qty_in_future_sle(args, allow_negative_stock=None):
allow_negative_stock = allow_negative_stock \
or cint(frappe.db.get_single_value("Stock Settings", "allow_negative_stock"))
- if args.actual_qty < 0 and not allow_negative_stock:
+ if (args.actual_qty < 0 or args.voucher_type == "Stock Reconciliation") and not allow_negative_stock:
sle = get_future_sle_with_negative_qty(args)
if sle:
message = _("{0} units of {1} needed in {2} on {3} {4} for {5} to complete this transaction.").format(
@@ -857,3 +1032,12 @@ def get_future_sle_with_negative_qty(args):
order by timestamp(posting_date, posting_time) asc
limit 1
""", args, as_dict=1)
+
+def _round_off_if_near_zero(number: float, precision: int = 6) -> float:
+ """ Rounds off the number to zero only if number is close to zero for decimal
+ specified in precision. Precision defaults to 6.
+ """
+ if flt(number) < (1.0 / (10**precision)):
+ return 0
+
+ return flt(number)
diff --git a/erpnext/stock/utils.py b/erpnext/stock/utils.py
index 0af3d908229..b57b2aa6b8f 100644
--- a/erpnext/stock/utils.py
+++ b/erpnext/stock/utils.py
@@ -172,12 +172,12 @@ def get_bin(item_code, warehouse):
bin_obj.flags.ignore_permissions = 1
bin_obj.insert()
else:
- bin_obj = frappe.get_cached_doc('Bin', bin)
+ bin_obj = frappe.get_doc('Bin', bin, for_update=True)
bin_obj.flags.ignore_permissions = True
return bin_obj
def update_bin(args, allow_negative_stock=False, via_landed_cost_voucher=False):
- is_stock_item = frappe.db.get_value('Item', args.get("item_code"), 'is_stock_item')
+ is_stock_item = frappe.get_cached_value('Item', args.get("item_code"), 'is_stock_item')
if is_stock_item:
bin = get_bin(args.get("item_code"), args.get("warehouse"))
bin.update_stock(args, allow_negative_stock, via_landed_cost_voucher)
@@ -314,13 +314,16 @@ def update_included_uom_in_report(columns, result, include_uom, conversion_facto
for row_idx, row in enumerate(result):
data = row.items() if is_dict_obj else enumerate(row)
for key, value in data:
- if key not in convertible_columns or not conversion_factors[row_idx-1]:
+ if key not in convertible_columns:
continue
+ # If no conversion factor for the UOM, defaults to 1
+ if not conversion_factors[row_idx]:
+ conversion_factors[row_idx] = 1
if convertible_columns.get(key) == 'rate':
- new_value = flt(value) * conversion_factors[row_idx-1]
+ new_value = flt(value) * conversion_factors[row_idx]
else:
- new_value = flt(value) / conversion_factors[row_idx-1]
+ new_value = flt(value) / conversion_factors[row_idx]
if not is_dict_obj:
row.insert(key+1, new_value)
@@ -386,4 +389,4 @@ def is_reposting_item_valuation_in_progress():
reposting_in_progress = frappe.db.exists("Repost Item Valuation",
{'docstatus': 1, 'status': ['in', ['Queued','In Progress']]})
if reposting_in_progress:
- frappe.msgprint(_("Item valuation reposting in progress. Report might show incorrect item valuation."), alert=1)
\ No newline at end of file
+ frappe.msgprint(_("Item valuation reposting in progress. Report might show incorrect item valuation."), alert=1)
diff --git a/erpnext/stock/workspace/stock/stock.json b/erpnext/stock/workspace/stock/stock.json
index 3221dc4365c..529ce8eb61e 100644
--- a/erpnext/stock/workspace/stock/stock.json
+++ b/erpnext/stock/workspace/stock/stock.json
@@ -15,6 +15,7 @@
"hide_custom": 0,
"icon": "stock",
"idx": 0,
+ "is_default": 0,
"is_standard": 1,
"label": "Stock",
"links": [
@@ -653,9 +654,44 @@
"link_type": "Report",
"onboard": 0,
"type": "Link"
+ },
+ {
+ "hidden": 0,
+ "is_query_report": 0,
+ "label": "Incorrect Data Report",
+ "link_type": "DocType",
+ "onboard": 0,
+ "type": "Card Break"
+ },
+ {
+ "hidden": 0,
+ "is_query_report": 0,
+ "label": "Incorrect Serial No Qty and Valuation",
+ "link_to": "Incorrect Serial No Valuation",
+ "link_type": "Report",
+ "onboard": 0,
+ "type": "Link"
+ },
+ {
+ "hidden": 0,
+ "is_query_report": 0,
+ "label": "Incorrect Balance Qty After Transaction",
+ "link_to": "Incorrect Balance Qty After Transaction",
+ "link_type": "Report",
+ "onboard": 0,
+ "type": "Link"
+ },
+ {
+ "hidden": 0,
+ "is_query_report": 0,
+ "label": "Stock and Account Value Comparison",
+ "link_to": "Stock and Account Value Comparison",
+ "link_type": "Report",
+ "onboard": 0,
+ "type": "Link"
}
],
- "modified": "2020-12-01 13:38:36.282890",
+ "modified": "2021-05-13 13:10:24.914983",
"modified_by": "Administrator",
"module": "Stock",
"name": "Stock",
diff --git a/erpnext/support/doctype/issue/issue.js b/erpnext/support/doctype/issue/issue.js
index 9fe12f9490b..ecc9fcfe829 100644
--- a/erpnext/support/doctype/issue/issue.js
+++ b/erpnext/support/doctype/issue/issue.js
@@ -48,44 +48,62 @@ frappe.ui.form.on("Issue", {
}
},
- refresh: function (frm) {
- if (frm.doc.status !== "Closed") {
- if (frm.doc.service_level_agreement && frm.doc.agreement_status === "Ongoing") {
- frappe.call({
- "method": "frappe.client.get",
- args: {
- doctype: "Service Level Agreement",
- name: frm.doc.service_level_agreement
- },
- callback: function(data) {
- let statuses = data.message.pause_sla_on;
- const hold_statuses = [];
- $.each(statuses, (_i, entry) => {
- hold_statuses.push(entry.status);
- });
- if (hold_statuses.includes(frm.doc.status)) {
- frm.dashboard.clear_headline();
- let message = {"indicator": "orange", "msg": __("SLA is on hold since {0}", [moment(frm.doc.on_hold_since).fromNow(true)])};
- frm.dashboard.set_headline_alert(
- '