Merge pull request #25104 from anupamvs/purchase-side-margin-beta
feat: price margin in buying
diff --git a/.flake8 b/.flake8
new file mode 100644
index 0000000..399b176
--- /dev/null
+++ b/.flake8
@@ -0,0 +1,32 @@
+[flake8]
+ignore =
+ E121,
+ E126,
+ E127,
+ E128,
+ E203,
+ E225,
+ E226,
+ E231,
+ E241,
+ E251,
+ E261,
+ E265,
+ E302,
+ E303,
+ E305,
+ E402,
+ E501,
+ E741,
+ W291,
+ W292,
+ W293,
+ W391,
+ W503,
+ W504,
+ F403,
+ B007,
+ B950,
+ W191,
+
+max-line-length = 200
\ No newline at end of file
diff --git a/erpnext/accounts/doctype/sales_invoice/sales_invoice.json b/erpnext/accounts/doctype/sales_invoice/sales_invoice.json
index 720a917..d382386 100644
--- a/erpnext/accounts/doctype/sales_invoice/sales_invoice.json
+++ b/erpnext/accounts/doctype/sales_invoice/sales_invoice.json
@@ -1952,13 +1952,12 @@
"is_submittable": 1,
"links": [
{
- "custom": 1,
"group": "Reference",
"link_doctype": "POS Invoice",
"link_fieldname": "consolidated_invoice"
}
],
- "modified": "2021-02-01 15:42:26.261540",
+ "modified": "2021-03-31 15:42:26.261540",
"modified_by": "Administrator",
"module": "Accounts",
"name": "Sales Invoice",
diff --git a/erpnext/controllers/stock_controller.py b/erpnext/controllers/stock_controller.py
index 11ac703..f352bae 100644
--- a/erpnext/controllers/stock_controller.py
+++ b/erpnext/controllers/stock_controller.py
@@ -495,7 +495,7 @@
"voucher_no": self.name,
"company": self.company
})
- if check_if_future_sle_exists(args):
+ if future_sle_exists(args):
create_repost_item_valuation_entry(args)
elif not is_reposting_pending():
check_if_stock_and_account_balance_synced(self.posting_date,
@@ -506,37 +506,42 @@
{'docstatus': 1, 'status': ['in', ['Queued','In Progress']]})
-def check_if_future_sle_exists(args):
- sl_entries = frappe.db.get_all("Stock Ledger Entry",
+def future_sle_exists(args):
+ sl_entries = frappe.get_all("Stock Ledger Entry",
filters={"voucher_type": args.voucher_type, "voucher_no": args.voucher_no},
fields=["item_code", "warehouse"],
order_by="creation asc")
- distinct_item_warehouses = list(set([(d.item_code, d.warehouse) for d in sl_entries]))
+ if not sl_entries:
+ return
- sle_exists = False
- for item_code, warehouse in distinct_item_warehouses:
- args.update({
- "item_code": item_code,
- "warehouse": warehouse
- })
- if get_sle(args):
- sle_exists = True
- break
- return sle_exists
+ warehouse_items_map = {}
+ for entry in sl_entries:
+ if entry.warehouse not in warehouse_items_map:
+ warehouse_items_map[entry.warehouse] = set()
-def get_sle(args):
+ warehouse_items_map[entry.warehouse].add(entry.item_code)
+
+ or_conditions = []
+ for warehouse, items in warehouse_items_map.items():
+ or_conditions.append(
+ "warehouse = '{}' and item_code in ({})".format(
+ warehouse,
+ ", ".join(frappe.db.escape(item) for item in items)
+ )
+ )
+
return frappe.db.sql("""
select name
from `tabStock Ledger Entry`
where
- item_code=%(item_code)s
- and warehouse=%(warehouse)s
- and timestamp(posting_date, posting_time) >= timestamp(%(posting_date)s, %(posting_time)s)
+ ({})
+ and timestamp(posting_date, posting_time)
+ >= timestamp(%(posting_date)s, %(posting_time)s)
and voucher_no != %(voucher_no)s
and is_cancelled = 0
limit 1
- """, args)
+ """.format(" or ".join(or_conditions)), args)
def create_repost_item_valuation_entry(args):
args = frappe._dict(args)
@@ -554,4 +559,4 @@
repost_entry.allow_zero_rate = args.allow_zero_rate
repost_entry.flags.ignore_links = True
repost_entry.save()
- repost_entry.submit()
\ No newline at end of file
+ repost_entry.submit()
diff --git a/erpnext/regional/italy/sales_invoice.js b/erpnext/regional/italy/sales_invoice.js
index 586a529..b54ac53 100644
--- a/erpnext/regional/italy/sales_invoice.js
+++ b/erpnext/regional/italy/sales_invoice.js
@@ -11,15 +11,10 @@
callback: function(r) {
frm.reload_doc();
if(r.message) {
- var w = window.open(
- frappe.urllib.get_full_url(
- "/api/method/erpnext.regional.italy.utils.download_e_invoice_file?"
- + "file_name=" + r.message
- )
- )
- if (!w) {
- frappe.msgprint(__("Please enable pop-ups")); return;
- }
+ open_url_post(frappe.request.url, {
+ cmd: 'frappe.core.doctype.file.file.download_file',
+ file_url: r.message
+ });
}
}
});
diff --git a/erpnext/regional/italy/setup.py b/erpnext/regional/italy/setup.py
index 95b92e7..a1f5bb9 100644
--- a/erpnext/regional/italy/setup.py
+++ b/erpnext/regional/italy/setup.py
@@ -128,11 +128,8 @@
fetch_from="company.vat_collectability"),
dict(fieldname='sb_e_invoicing_reference', label='E-Invoicing',
fieldtype='Section Break', insert_after='against_income_account', print_hide=1),
- dict(fieldname='company_tax_id', label='Company Tax ID',
- fieldtype='Data', insert_after='sb_e_invoicing_reference', print_hide=1, read_only=1,
- fetch_from="company.tax_id"),
dict(fieldname='company_fiscal_code', label='Company Fiscal Code',
- fieldtype='Data', insert_after='company_tax_id', print_hide=1, read_only=1,
+ fieldtype='Data', insert_after='sb_e_invoicing_reference', print_hide=1, read_only=1,
fetch_from="company.fiscal_code"),
dict(fieldname='company_fiscal_regime', label='Company Fiscal Regime',
fieldtype='Data', insert_after='company_fiscal_code', print_hide=1, read_only=1,
@@ -217,4 +214,4 @@
update_permission_property(doctype, 'Accounts Manager', 0, 'delete', 1)
add_permission(doctype, 'Accounts Manager', 1)
update_permission_property(doctype, 'Accounts Manager', 1, 'write', 1)
- update_permission_property(doctype, 'Accounts Manager', 1, 'create', 1)
\ No newline at end of file
+ update_permission_property(doctype, 'Accounts Manager', 1, 'create', 1)
diff --git a/erpnext/regional/italy/utils.py b/erpnext/regional/italy/utils.py
index 6842fb2..08573cd 100644
--- a/erpnext/regional/italy/utils.py
+++ b/erpnext/regional/italy/utils.py
@@ -1,6 +1,8 @@
from __future__ import unicode_literals
-import frappe, json, os
+import io
+import json
+import frappe
from frappe.utils import flt, cstr
from erpnext.controllers.taxes_and_totals import get_itemised_tax
from frappe import _
@@ -28,20 +30,22 @@
@frappe.whitelist()
def export_invoices(filters=None):
- saved_xmls = []
+ frappe.has_permission('Sales Invoice', throw=True)
- invoices = frappe.get_all("Sales Invoice", filters=get_conditions(filters), fields=["*"])
+ invoices = frappe.get_all(
+ "Sales Invoice",
+ filters=get_conditions(filters),
+ fields=["name", "company_tax_id"]
+ )
- for invoice in invoices:
- attachments = get_e_invoice_attachments(invoice)
- saved_xmls += [attachment.file_name for attachment in attachments]
+ attachments = get_e_invoice_attachments(invoices)
- zip_filename = "{0}-einvoices.zip".format(frappe.utils.get_datetime().strftime("%Y%m%d_%H%M%S"))
+ zip_filename = "{0}-einvoices.zip".format(
+ frappe.utils.get_datetime().strftime("%Y%m%d_%H%M%S"))
- download_zip(saved_xmls, zip_filename)
+ download_zip(attachments, zip_filename)
-@frappe.whitelist()
def prepare_invoice(invoice, progressive_number):
#set company information
company = frappe.get_doc("Company", invoice.company)
@@ -98,7 +102,7 @@
def get_conditions(filters):
filters = json.loads(filters)
- conditions = {"docstatus": 1}
+ conditions = {"docstatus": 1, "company_tax_id": ("!=", "")}
if filters.get("company"): conditions["company"] = filters["company"]
if filters.get("customer"): conditions["customer"] = filters["customer"]
@@ -111,23 +115,22 @@
return conditions
-#TODO: Use function from frappe once PR #6853 is merged.
+
def download_zip(files, output_filename):
- from zipfile import ZipFile
+ import zipfile
- input_files = [frappe.get_site_path('private', 'files', filename) for filename in files]
- output_path = frappe.get_site_path('private', 'files', output_filename)
+ zip_stream = io.BytesIO()
+ with zipfile.ZipFile(zip_stream, 'w', zipfile.ZIP_DEFLATED) as zip_file:
+ for file in files:
+ file_path = frappe.utils.get_files_path(
+ file.file_name, is_private=file.is_private)
- with ZipFile(output_path, 'w') as output_zip:
- for input_file in input_files:
- output_zip.write(input_file, arcname=os.path.basename(input_file))
-
- with open(output_path, 'rb') as fileobj:
- filedata = fileobj.read()
+ zip_file.write(file_path, arcname=file.file_name)
frappe.local.response.filename = output_filename
- frappe.local.response.filecontent = filedata
+ frappe.local.response.filecontent = zip_stream.getvalue()
frappe.local.response.type = "download"
+ zip_stream.close()
def get_invoice_summary(items, taxes):
summary_data = frappe._dict()
@@ -307,23 +310,12 @@
@frappe.whitelist()
def generate_single_invoice(docname):
doc = frappe.get_doc("Sales Invoice", docname)
-
+ frappe.has_permission("Sales Invoice", doc=doc, throw=True)
e_invoice = prepare_and_attach_invoice(doc, True)
+ return e_invoice.file_url
- return e_invoice.file_name
-
-@frappe.whitelist()
-def download_e_invoice_file(file_name):
- content = None
- with open(frappe.get_site_path('private', 'files', file_name), "r") as f:
- content = f.read()
-
- frappe.local.response.filename = file_name
- frappe.local.response.filecontent = content
- frappe.local.response.type = "download"
-
-#Delete e-invoice attachment on cancel.
+# Delete e-invoice attachment on cancel.
def sales_invoice_on_cancel(doc, method):
if get_company_country(doc.company) not in ['Italy',
'Italia', 'Italian Republic', 'Repubblica Italiana']:
@@ -335,16 +327,38 @@
def get_company_country(company):
return frappe.get_cached_value('Company', company, 'country')
-def get_e_invoice_attachments(invoice):
- if not invoice.company_tax_id:
- return []
+def get_e_invoice_attachments(invoices):
+ if not isinstance(invoices, list):
+ if not invoices.company_tax_id:
+ return
+
+ invoices = [invoices]
+
+ tax_id_map = {
+ invoice.name: (
+ invoice.company_tax_id
+ if invoice.company_tax_id.startswith("IT")
+ else "IT" + invoice.company_tax_id
+ ) for invoice in invoices
+ }
+
+ attachments = frappe.get_all(
+ "File",
+ fields=("name", "file_name", "attached_to_name", "is_private"),
+ filters= {
+ "attached_to_name": ('in', tax_id_map),
+ "attached_to_doctype": 'Sales Invoice'
+ }
+ )
out = []
- attachments = get_attachments(invoice.doctype, invoice.name)
- company_tax_id = invoice.company_tax_id if invoice.company_tax_id.startswith("IT") else "IT" + invoice.company_tax_id
-
for attachment in attachments:
- if attachment.file_name and attachment.file_name.startswith(company_tax_id) and attachment.file_name.endswith(".xml"):
+ if (
+ attachment.file_name
+ and attachment.file_name.endswith(".xml")
+ and attachment.file_name.startswith(
+ tax_id_map.get(attachment.attached_to_name))
+ ):
out.append(attachment)
return out
diff --git a/erpnext/selling/doctype/sales_order/sales_order.py b/erpnext/selling/doctype/sales_order/sales_order.py
index e561291..af3d461 100755
--- a/erpnext/selling/doctype/sales_order/sales_order.py
+++ b/erpnext/selling/doctype/sales_order/sales_order.py
@@ -778,6 +778,7 @@
@frappe.whitelist()
def make_purchase_order_for_default_supplier(source_name, selected_items=None, target_doc=None):
+ """Creates Purchase Order for each Supplier. Returns a list of doc objects."""
if not selected_items: return
if isinstance(selected_items, string_types):
@@ -820,15 +821,16 @@
target.stock_qty = (flt(source.stock_qty) - flt(source.ordered_qty))
target.project = source_parent.project
- suppliers = [item.get('supplier') for item in selected_items if item.get('supplier') and item.get('supplier')]
- suppliers = list(set(suppliers))
+ suppliers = [item.get('supplier') for item in selected_items if item.get('supplier')]
+ suppliers = list(dict.fromkeys(suppliers)) # remove duplicates while preserving order
- items_to_map = [item.get('item_code') for item in selected_items if item.get('item_code') and item.get('item_code')]
+ items_to_map = [item.get('item_code') for item in selected_items if item.get('item_code')]
items_to_map = list(set(items_to_map))
if not suppliers:
frappe.throw(_("Please set a Supplier against the Items to be considered in the Purchase Order."))
+ purchase_orders = []
for supplier in suppliers:
doc = get_mapped_doc("Sales Order", source_name, {
"Sales Order": {
@@ -872,7 +874,9 @@
doc.insert()
frappe.db.commit()
- return doc
+ purchase_orders.append(doc)
+
+ return purchase_orders
@frappe.whitelist()
def make_purchase_order(source_name, selected_items=None, target_doc=None):
diff --git a/erpnext/selling/doctype/sales_order/test_sales_order.py b/erpnext/selling/doctype/sales_order/test_sales_order.py
index ee16f44..b636a94 100644
--- a/erpnext/selling/doctype/sales_order/test_sales_order.py
+++ b/erpnext/selling/doctype/sales_order/test_sales_order.py
@@ -743,7 +743,7 @@
so = make_sales_order(item_list=so_items, do_not_submit=True)
so.submit()
- po = make_purchase_order_for_default_supplier(so.name, selected_items=[so_items[0]])
+ po = make_purchase_order_for_default_supplier(so.name, selected_items=[so_items[0]])[0]
po.submit()
dn = create_dn_against_so(so.name, delivered_qty=2)
@@ -825,7 +825,7 @@
so.submit()
# create po for only one item
- po1 = make_purchase_order_for_default_supplier(so.name, selected_items=[so_items[0]])
+ po1 = make_purchase_order_for_default_supplier(so.name, selected_items=[so_items[0]])[0]
po1.submit()
self.assertEqual(so.customer, po1.customer)
@@ -835,7 +835,7 @@
self.assertEqual(len(po1.items), 1)
# create po for remaining item
- po2 = make_purchase_order_for_default_supplier(so.name, selected_items=[so_items[1]])
+ po2 = make_purchase_order_for_default_supplier(so.name, selected_items=[so_items[1]])[0]
po2.submit()
# teardown
@@ -846,6 +846,45 @@
so.load_from_db()
so.cancel()
+ def test_drop_shipping_full_for_default_suppliers(self):
+ """Test if multiple POs are generated in one go against different default suppliers."""
+ from erpnext.selling.doctype.sales_order.sales_order import make_purchase_order_for_default_supplier
+
+ if not frappe.db.exists("Item", "_Test Item for Drop Shipping 1"):
+ make_item("_Test Item for Drop Shipping 1", {"is_stock_item": 1, "delivered_by_supplier": 1})
+
+ if not frappe.db.exists("Item", "_Test Item for Drop Shipping 2"):
+ make_item("_Test Item for Drop Shipping 2", {"is_stock_item": 1, "delivered_by_supplier": 1})
+
+ so_items = [
+ {
+ "item_code": "_Test Item for Drop Shipping 1",
+ "warehouse": "",
+ "qty": 2,
+ "rate": 400,
+ "delivered_by_supplier": 1,
+ "supplier": '_Test Supplier'
+ },
+ {
+ "item_code": "_Test Item for Drop Shipping 2",
+ "warehouse": "",
+ "qty": 2,
+ "rate": 400,
+ "delivered_by_supplier": 1,
+ "supplier": '_Test Supplier 1'
+ }
+ ]
+
+ # create so and po
+ so = make_sales_order(item_list=so_items, do_not_submit=True)
+ so.submit()
+
+ purchase_orders = make_purchase_order_for_default_supplier(so.name, selected_items=so_items)
+
+ self.assertEqual(len(purchase_orders), 2)
+ self.assertEqual(purchase_orders[0].supplier, '_Test Supplier')
+ self.assertEqual(purchase_orders[1].supplier, '_Test Supplier 1')
+
def test_reserved_qty_for_closing_so(self):
bin = frappe.get_all("Bin", filters={"item_code": "_Test Item", "warehouse": "_Test Warehouse - _TC"},
fields=["reserved_qty"])
diff --git a/erpnext/selling/page/point_of_sale/pos_past_order_summary.js b/erpnext/selling/page/point_of_sale/pos_past_order_summary.js
index 39f54fa..a5a739c 100644
--- a/erpnext/selling/page/point_of_sale/pos_past_order_summary.js
+++ b/erpnext/selling/page/point_of_sale/pos_past_order_summary.js
@@ -64,10 +64,7 @@
{fieldname: 'print', fieldtype: 'Data', label: 'Print Preview'}
],
primary_action: () => {
- const frm = this.events.get_frm();
- frm.doc = this.doc;
- frm.print_preview.lang_code = frm.doc.language;
- frm.print_preview.printit(true);
+ this.print_receipt();
},
primary_action_label: __('Print'),
});
@@ -200,13 +197,21 @@
});
this.$summary_container.on('click', '.print-btn', () => {
- const frm = this.events.get_frm();
- frm.doc = this.doc;
- frm.print_preview.lang_code = frm.doc.language;
- frm.print_preview.printit(true);
+ this.print_receipt();
});
}
+ print_receipt() {
+ const frm = this.events.get_frm();
+ frappe.utils.print(
+ frm.doctype,
+ frm.docname,
+ frm.pos_print_format,
+ frm.doc.letter_head,
+ frm.doc.language || frappe.boot.lang
+ );
+ }
+
attach_shortcuts() {
const ctrl_label = frappe.utils.is_mac() ? '⌘' : 'Ctrl';
this.$summary_container.find('.print-btn').attr("title", `${ctrl_label}+P`);
diff --git a/erpnext/stock/doctype/delivery_note/delivery_note.py b/erpnext/stock/doctype/delivery_note/delivery_note.py
index 3544390..d326a04 100644
--- a/erpnext/stock/doctype/delivery_note/delivery_note.py
+++ b/erpnext/stock/doctype/delivery_note/delivery_note.py
@@ -101,7 +101,7 @@
for f in fieldname:
toggle_print_hide(self.meta if key == "parent" else item_meta, f)
- super(DeliveryNote, self).before_print()
+ super(DeliveryNote, self).before_print(settings)
def set_actual_qty(self):
for d in self.get('items'):
diff --git a/erpnext/stock/doctype/stock_entry/stock_entry.js b/erpnext/stock/doctype/stock_entry/stock_entry.js
index 4979234..af3c4e5 100644
--- a/erpnext/stock/doctype/stock_entry/stock_entry.js
+++ b/erpnext/stock/doctype/stock_entry/stock_entry.js
@@ -848,7 +848,6 @@
}
erpnext.hide_company();
erpnext.utils.add_item(this.frm);
- this.frm.trigger('add_to_transit');
},
scan_barcode: function() {
diff --git a/erpnext/stock/stock_ledger.py b/erpnext/stock/stock_ledger.py
index f54b3c1..121c51c 100644
--- a/erpnext/stock/stock_ledger.py
+++ b/erpnext/stock/stock_ledger.py
@@ -207,11 +207,11 @@
def build(self):
- from erpnext.controllers.stock_controller import check_if_future_sle_exists
+ from erpnext.controllers.stock_controller import future_sle_exists
if self.args.get("sle_id"):
self.process_sle_against_current_timestamp()
- if not check_if_future_sle_exists(self.args):
+ if not future_sle_exists(self.args):
self.update_bin()
else:
entries_to_fix = self.get_future_entries_to_fix()
@@ -856,4 +856,4 @@
and qty_after_transaction < 0
order by timestamp(posting_date, posting_time) asc
limit 1
- """, args, as_dict=1)
\ No newline at end of file
+ """, args, as_dict=1)
diff --git a/sider.yml b/sider.yml
new file mode 100644
index 0000000..2ca6e8d
--- /dev/null
+++ b/sider.yml
@@ -0,0 +1,3 @@
+linter:
+ flake8:
+ config: .flake8
\ No newline at end of file