Auto fetch batches based on quantity on POS (#11004) (#11767)

* prevent premature escape when item has serial no and batch no

* fetch actual_batch_qty for item

* add available_qty to dialog

* remove expired batches from drop-down

* Update queries.py
diff --git a/erpnext/controllers/queries.py b/erpnext/controllers/queries.py
index 353721e..a71a08e 100644
--- a/erpnext/controllers/queries.py
+++ b/erpnext/controllers/queries.py
@@ -410,3 +410,14 @@
 	for row in filters:
 		filter_dict[row[0]].append(row)
 	return filter_dict
+
+
+@frappe.whitelist()
+def get_batch_numbers(doctype, txt, searchfield, start, page_len, filters):
+	query = 'select batch_id from `tabBatch` ' \
+			'where (`tabBatch`.expiry_date >= CURDATE() or `tabBatch`.expiry_date IS NULL)'
+
+	if filters and filters.get('item_code'):
+		query += 'where item = %(item_code)s' % filters
+
+	return frappe.db.sql(query)
diff --git a/erpnext/public/js/utils/serial_no_batch_selector.js b/erpnext/public/js/utils/serial_no_batch_selector.js
index 69e3d2f..f348746 100644
--- a/erpnext/public/js/utils/serial_no_batch_selector.js
+++ b/erpnext/public/js/utils/serial_no_batch_selector.js
@@ -98,11 +98,14 @@
 			let d = this.item;
 			if (d.has_serial_no && d.serial_no) {
 				this.dialog.set_value('serial_no', d.serial_no);
-			} else if (d.batch_no) {
+			}
+
+			if (d.batch_no) {
 				this.dialog.fields_dict.batches.df.data.push({
 					'batch_no': d.batch_no,
 					'actual_qty': d.actual_qty,
-					'selected_qty': d.qty
+					'selected_qty': d.qty,
+					'available_qty': d.actual_batch_qty
 				});
 
 				this.dialog.fields_dict.batches.grid.refresh();
@@ -204,7 +207,10 @@
 						label: __('Select Batch'),
 						in_list_view:1,
 						get_query: function() {
-							return {filters: {item: me.item_code }};
+							return {
+							    filters: {item: me.item_code },
+							    query: 'erpnext.controllers.queries.get_batch_numbers'
+					        };
 						},
 						onchange: function(e) {
 							let val = this.get_value();
diff --git a/erpnext/stock/get_item_details.py b/erpnext/stock/get_item_details.py
index 63c76bc..50a080d 100644
--- a/erpnext/stock/get_item_details.py
+++ b/erpnext/stock/get_item_details.py
@@ -84,6 +84,7 @@
 
 		if out.has_batch_no and not args.get("batch_no"):
 			out.batch_no = get_batch_no(out.item_code, out.warehouse, out.qty)
+			out.update(get_batch_qty(out.batch_no, out.warehouse, out.item_code))
 
 	if args.transaction_date and item.lead_time_days:
 		out.schedule_date = out.lead_time_date = add_days(args.transaction_date,