Anand Doshi | 885e074 | 2015-03-03 14:55:30 +0530 | [diff] [blame] | 1 | # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors |
Rushabh Mehta | e67d1fb | 2013-08-05 14:59:54 +0530 | [diff] [blame] | 2 | # License: GNU General Public License v3. See license.txt |
Nabin Hait | 902e860 | 2013-01-08 18:29:24 +0530 | [diff] [blame] | 3 | |
Rohit Waghchaure | bb3e5d0 | 2021-04-24 17:28:33 +0530 | [diff] [blame] | 4 | import copy |
Nabin Hait | 26d4655 | 2013-01-09 15:23:05 +0530 | [diff] [blame] | 5 | import json |
Ankush Menat | eb8b424 | 2022-02-12 13:08:28 +0530 | [diff] [blame] | 6 | from typing import Optional |
Chillar Anand | 915b343 | 2021-09-02 16:44:59 +0530 | [diff] [blame] | 7 | |
| 8 | import frappe |
| 9 | from frappe import _ |
| 10 | from frappe.model.meta import get_field_precision |
Ankush Menat | 102fff2 | 2022-02-19 15:51:04 +0530 | [diff] [blame] | 11 | from frappe.query_builder.functions import Sum |
Ankush Menat | cef84c2 | 2021-12-03 12:18:59 +0530 | [diff] [blame] | 12 | from frappe.utils import cint, cstr, flt, get_link_to_form, getdate, now, nowdate |
Ankush Menat | 102fff2 | 2022-02-19 15:51:04 +0530 | [diff] [blame] | 13 | from pypika import CustomFunction |
Achilles Rasquinha | 361366e | 2018-02-14 17:08:59 +0530 | [diff] [blame] | 14 | |
Chillar Anand | 915b343 | 2021-09-02 16:44:59 +0530 | [diff] [blame] | 15 | import erpnext |
Ankush Menat | cef84c2 | 2021-12-03 12:18:59 +0530 | [diff] [blame] | 16 | from erpnext.stock.doctype.bin.bin import update_qty as update_bin_qty |
Chillar Anand | 915b343 | 2021-09-02 16:44:59 +0530 | [diff] [blame] | 17 | from erpnext.stock.utils import ( |
Chillar Anand | 915b343 | 2021-09-02 16:44:59 +0530 | [diff] [blame] | 18 | get_incoming_outgoing_rate_for_cancel, |
Deepesh Garg | 6f107da | 2021-10-12 20:15:55 +0530 | [diff] [blame] | 19 | get_or_make_bin, |
Chillar Anand | 915b343 | 2021-09-02 16:44:59 +0530 | [diff] [blame] | 20 | get_valuation_method, |
| 21 | ) |
Ankush Menat | b534fee | 2022-02-19 20:58:36 +0530 | [diff] [blame] | 22 | from erpnext.stock.valuation import FIFOValuation, LIFOValuation, round_off_if_near_zero |
Chillar Anand | 915b343 | 2021-09-02 16:44:59 +0530 | [diff] [blame] | 23 | |
Nabin Hait | 97bce3a | 2021-07-12 13:24:43 +0530 | [diff] [blame] | 24 | |
Rushabh Mehta | 793ba6b | 2014-02-14 15:47:51 +0530 | [diff] [blame] | 25 | class NegativeStockError(frappe.ValidationError): pass |
Rohit Waghchaure | bb3e5d0 | 2021-04-24 17:28:33 +0530 | [diff] [blame] | 26 | class SerialNoExistsInFutureTransaction(frappe.ValidationError): |
| 27 | pass |
Nabin Hait | 902e860 | 2013-01-08 18:29:24 +0530 | [diff] [blame] | 28 | |
Anand Doshi | 5b004ff | 2013-09-25 19:55:41 +0530 | [diff] [blame] | 29 | |
Deepesh Garg | 2a9c5ba | 2020-04-30 10:38:58 +0530 | [diff] [blame] | 30 | def make_sl_entries(sl_entries, allow_negative_stock=False, via_landed_cost_voucher=False): |
Ankush Menat | eb8495a | 2022-03-02 12:01:51 +0530 | [diff] [blame] | 31 | """ Create SL entries from SL entry dicts |
| 32 | |
| 33 | args: |
| 34 | - allow_negative_stock: disable negative stock valiations if true |
| 35 | - via_landed_cost_voucher: landed cost voucher cancels and reposts |
| 36 | entries of purchase document. This flag is used to identify if |
| 37 | cancellation and repost is happening via landed cost voucher, in |
| 38 | such cases certain validations need to be ignored (like negative |
| 39 | stock) |
| 40 | """ |
Rohit Waghchaure | 4d81d45 | 2021-06-15 10:21:44 +0530 | [diff] [blame] | 41 | from erpnext.controllers.stock_controller import future_sle_exists |
Nabin Hait | ca77574 | 2013-09-26 16:16:44 +0530 | [diff] [blame] | 42 | if sl_entries: |
Deepesh Garg | 2a9c5ba | 2020-04-30 10:38:58 +0530 | [diff] [blame] | 43 | cancel = sl_entries[0].get("is_cancelled") |
Nabin Hait | ca77574 | 2013-09-26 16:16:44 +0530 | [diff] [blame] | 44 | if cancel: |
Nabin Hait | 186a045 | 2021-02-18 14:14:21 +0530 | [diff] [blame] | 45 | validate_cancellation(sl_entries) |
Deepesh Garg | 2a9c5ba | 2020-04-30 10:38:58 +0530 | [diff] [blame] | 46 | set_as_cancel(sl_entries[0].get('voucher_type'), sl_entries[0].get('voucher_no')) |
Nabin Hait | dc82d4f | 2014-04-07 12:02:57 +0530 | [diff] [blame] | 47 | |
Rohit Waghchaure | 4d81d45 | 2021-06-15 10:21:44 +0530 | [diff] [blame] | 48 | args = get_args_for_future_sle(sl_entries[0]) |
| 49 | future_sle_exists(args, sl_entries) |
| 50 | |
Nabin Hait | ca77574 | 2013-09-26 16:16:44 +0530 | [diff] [blame] | 51 | for sle in sl_entries: |
Ankush Menat | efc4b94 | 2022-03-02 11:19:12 +0530 | [diff] [blame] | 52 | if sle.serial_no and not via_landed_cost_voucher: |
Rohit Waghchaure | bb3e5d0 | 2021-04-24 17:28:33 +0530 | [diff] [blame] | 53 | validate_serial_no(sle) |
| 54 | |
Nabin Hait | a77b8c9 | 2020-12-21 14:45:50 +0530 | [diff] [blame] | 55 | if cancel: |
| 56 | sle['actual_qty'] = -flt(sle.get('actual_qty')) |
Deepesh Garg | 2a9c5ba | 2020-04-30 10:38:58 +0530 | [diff] [blame] | 57 | |
Nabin Hait | a77b8c9 | 2020-12-21 14:45:50 +0530 | [diff] [blame] | 58 | if sle['actual_qty'] < 0 and not sle.get('outgoing_rate'): |
| 59 | sle['outgoing_rate'] = get_incoming_outgoing_rate_for_cancel(sle.item_code, |
| 60 | sle.voucher_type, sle.voucher_no, sle.voucher_detail_no) |
| 61 | sle['incoming_rate'] = 0.0 |
Deepesh Garg | 2a9c5ba | 2020-04-30 10:38:58 +0530 | [diff] [blame] | 62 | |
Nabin Hait | a77b8c9 | 2020-12-21 14:45:50 +0530 | [diff] [blame] | 63 | if sle['actual_qty'] > 0 and not sle.get('incoming_rate'): |
| 64 | sle['incoming_rate'] = get_incoming_outgoing_rate_for_cancel(sle.item_code, |
| 65 | sle.voucher_type, sle.voucher_no, sle.voucher_detail_no) |
| 66 | sle['outgoing_rate'] = 0.0 |
Nabin Hait | dc82d4f | 2014-04-07 12:02:57 +0530 | [diff] [blame] | 67 | |
Nabin Hait | 5288bde | 2014-11-03 15:08:21 +0530 | [diff] [blame] | 68 | if sle.get("actual_qty") or sle.get("voucher_type")=="Stock Reconciliation": |
Nabin Hait | a77b8c9 | 2020-12-21 14:45:50 +0530 | [diff] [blame] | 69 | sle_doc = make_entry(sle, allow_negative_stock, via_landed_cost_voucher) |
Deepesh Garg | b4be292 | 2021-01-28 13:09:56 +0530 | [diff] [blame] | 70 | |
Nabin Hait | a77b8c9 | 2020-12-21 14:45:50 +0530 | [diff] [blame] | 71 | args = sle_doc.as_dict() |
marination | 4038977 | 2021-07-02 17:13:45 +0530 | [diff] [blame] | 72 | |
| 73 | if sle.get("voucher_type") == "Stock Reconciliation": |
| 74 | # preserve previous_qty_after_transaction for qty reposting |
| 75 | args.previous_qty_after_transaction = sle.get("previous_qty_after_transaction") |
| 76 | |
Ankush Menat | cef84c2 | 2021-12-03 12:18:59 +0530 | [diff] [blame] | 77 | is_stock_item = frappe.get_cached_value('Item', args.get("item_code"), 'is_stock_item') |
| 78 | if is_stock_item: |
| 79 | bin_name = get_or_make_bin(args.get("item_code"), args.get("warehouse")) |
Ankush Menat | cef84c2 | 2021-12-03 12:18:59 +0530 | [diff] [blame] | 80 | repost_current_voucher(args, allow_negative_stock, via_landed_cost_voucher) |
Ankush Menat | ff9a6e8 | 2021-12-20 15:07:41 +0530 | [diff] [blame] | 81 | update_bin_qty(bin_name, args) |
Ankush Menat | cef84c2 | 2021-12-03 12:18:59 +0530 | [diff] [blame] | 82 | else: |
| 83 | frappe.msgprint(_("Item {0} ignored since it is not a stock item").format(args.get("item_code"))) |
| 84 | |
| 85 | def repost_current_voucher(args, allow_negative_stock=False, via_landed_cost_voucher=False): |
| 86 | if args.get("actual_qty") or args.get("voucher_type") == "Stock Reconciliation": |
| 87 | if not args.get("posting_date"): |
| 88 | args["posting_date"] = nowdate() |
| 89 | |
| 90 | if args.get("is_cancelled") and via_landed_cost_voucher: |
| 91 | return |
| 92 | |
| 93 | # Reposts only current voucher SL Entries |
| 94 | # Updates valuation rate, stock value, stock queue for current transaction |
| 95 | update_entries_after({ |
| 96 | "item_code": args.get('item_code'), |
| 97 | "warehouse": args.get('warehouse'), |
| 98 | "posting_date": args.get("posting_date"), |
| 99 | "posting_time": args.get("posting_time"), |
| 100 | "voucher_type": args.get("voucher_type"), |
| 101 | "voucher_no": args.get("voucher_no"), |
| 102 | "sle_id": args.get('name'), |
| 103 | "creation": args.get('creation') |
| 104 | }, allow_negative_stock=allow_negative_stock, via_landed_cost_voucher=via_landed_cost_voucher) |
| 105 | |
| 106 | # update qty in future sle and Validate negative qty |
| 107 | update_qty_in_future_sle(args, allow_negative_stock) |
| 108 | |
Nabin Hait | adeb976 | 2014-10-06 11:53:52 +0530 | [diff] [blame] | 109 | |
Rohit Waghchaure | 4d81d45 | 2021-06-15 10:21:44 +0530 | [diff] [blame] | 110 | def get_args_for_future_sle(row): |
| 111 | return frappe._dict({ |
| 112 | 'voucher_type': row.get('voucher_type'), |
| 113 | 'voucher_no': row.get('voucher_no'), |
| 114 | 'posting_date': row.get('posting_date'), |
| 115 | 'posting_time': row.get('posting_time') |
| 116 | }) |
| 117 | |
Rohit Waghchaure | bb3e5d0 | 2021-04-24 17:28:33 +0530 | [diff] [blame] | 118 | def validate_serial_no(sle): |
| 119 | from erpnext.stock.doctype.serial_no.serial_no import get_serial_nos |
Ankush Menat | 66bf21f | 2022-01-16 20:45:59 +0530 | [diff] [blame] | 120 | |
Rohit Waghchaure | bb3e5d0 | 2021-04-24 17:28:33 +0530 | [diff] [blame] | 121 | for sn in get_serial_nos(sle.serial_no): |
| 122 | args = copy.deepcopy(sle) |
| 123 | args.serial_no = sn |
| 124 | args.warehouse = '' |
| 125 | |
| 126 | vouchers = [] |
| 127 | for row in get_stock_ledger_entries(args, '>'): |
| 128 | voucher_type = frappe.bold(row.voucher_type) |
| 129 | voucher_no = frappe.bold(get_link_to_form(row.voucher_type, row.voucher_no)) |
| 130 | vouchers.append(f'{voucher_type} {voucher_no}') |
| 131 | |
| 132 | if vouchers: |
| 133 | serial_no = frappe.bold(sn) |
| 134 | msg = (f'''The serial no {serial_no} has been used in the future transactions so you need to cancel them first. |
| 135 | The list of the transactions are as below.''' + '<br><br><ul><li>') |
| 136 | |
| 137 | msg += '</li><li>'.join(vouchers) |
| 138 | msg += '</li></ul>' |
| 139 | |
| 140 | title = 'Cannot Submit' if not sle.get('is_cancelled') else 'Cannot Cancel' |
| 141 | frappe.throw(_(msg), title=_(title), exc=SerialNoExistsInFutureTransaction) |
| 142 | |
Nabin Hait | 186a045 | 2021-02-18 14:14:21 +0530 | [diff] [blame] | 143 | def validate_cancellation(args): |
| 144 | if args[0].get("is_cancelled"): |
| 145 | repost_entry = frappe.db.get_value("Repost Item Valuation", { |
| 146 | 'voucher_type': args[0].voucher_type, |
| 147 | 'voucher_no': args[0].voucher_no, |
| 148 | 'docstatus': 1 |
| 149 | }, ['name', 'status'], as_dict=1) |
| 150 | |
| 151 | if repost_entry: |
| 152 | if repost_entry.status == 'In Progress': |
| 153 | frappe.throw(_("Cannot cancel the transaction. Reposting of item valuation on submission is not completed yet.")) |
| 154 | if repost_entry.status == 'Queued': |
Nabin Hait | d46b236 | 2021-02-23 16:38:52 +0530 | [diff] [blame] | 155 | doc = frappe.get_doc("Repost Item Valuation", repost_entry.name) |
Ankush Menat | aa024fc | 2021-11-18 12:51:26 +0530 | [diff] [blame] | 156 | doc.flags.ignore_permissions = True |
Nabin Hait | d46b236 | 2021-02-23 16:38:52 +0530 | [diff] [blame] | 157 | doc.cancel() |
| 158 | doc.delete() |
Nabin Hait | dc82d4f | 2014-04-07 12:02:57 +0530 | [diff] [blame] | 159 | |
Nabin Hait | 9653f60 | 2013-08-20 15:37:33 +0530 | [diff] [blame] | 160 | def set_as_cancel(voucher_type, voucher_no): |
Deepesh Garg | 2a9c5ba | 2020-04-30 10:38:58 +0530 | [diff] [blame] | 161 | frappe.db.sql("""update `tabStock Ledger Entry` set is_cancelled=1, |
Nabin Hait | 9653f60 | 2013-08-20 15:37:33 +0530 | [diff] [blame] | 162 | modified=%s, modified_by=%s |
Deepesh Garg | 2a9c5ba | 2020-04-30 10:38:58 +0530 | [diff] [blame] | 163 | where voucher_type=%s and voucher_no=%s and is_cancelled = 0""", |
Rushabh Mehta | 793ba6b | 2014-02-14 15:47:51 +0530 | [diff] [blame] | 164 | (now(), frappe.session.user, voucher_type, voucher_no)) |
Nabin Hait | dc82d4f | 2014-04-07 12:02:57 +0530 | [diff] [blame] | 165 | |
Nabin Hait | 54c865e | 2015-03-27 15:38:31 +0530 | [diff] [blame] | 166 | def make_entry(args, allow_negative_stock=False, via_landed_cost_voucher=False): |
Saqib Ansari | c7fc609 | 2021-10-12 13:30:40 +0530 | [diff] [blame] | 167 | args["doctype"] = "Stock Ledger Entry" |
Rushabh Mehta | a504f06 | 2014-04-04 12:16:26 +0530 | [diff] [blame] | 168 | sle = frappe.get_doc(args) |
Anand Doshi | 6dfd430 | 2015-02-10 14:41:27 +0530 | [diff] [blame] | 169 | sle.flags.ignore_permissions = 1 |
Nabin Hait | 4ccd8d3 | 2015-01-23 12:18:01 +0530 | [diff] [blame] | 170 | sle.allow_negative_stock=allow_negative_stock |
Nabin Hait | 54c865e | 2015-03-27 15:38:31 +0530 | [diff] [blame] | 171 | sle.via_landed_cost_voucher = via_landed_cost_voucher |
Nabin Hait | aeba24e | 2013-08-23 15:17:36 +0530 | [diff] [blame] | 172 | sle.submit() |
Nabin Hait | a77b8c9 | 2020-12-21 14:45:50 +0530 | [diff] [blame] | 173 | return sle |
Nabin Hait | dc82d4f | 2014-04-07 12:02:57 +0530 | [diff] [blame] | 174 | |
rohitwaghchaure | 31fe5f5 | 2021-08-02 11:01:30 +0530 | [diff] [blame] | 175 | def repost_future_sle(args=None, voucher_type=None, voucher_no=None, allow_negative_stock=None, via_landed_cost_voucher=False, doc=None): |
Nabin Hait | a77b8c9 | 2020-12-21 14:45:50 +0530 | [diff] [blame] | 176 | if not args and voucher_type and voucher_no: |
rohitwaghchaure | 31fe5f5 | 2021-08-02 11:01:30 +0530 | [diff] [blame] | 177 | args = get_items_to_be_repost(voucher_type, voucher_no, doc) |
Deepesh Garg | b4be292 | 2021-01-28 13:09:56 +0530 | [diff] [blame] | 178 | |
rohitwaghchaure | 31fe5f5 | 2021-08-02 11:01:30 +0530 | [diff] [blame] | 179 | distinct_item_warehouses = get_distinct_item_warehouse(args, doc) |
Nabin Hait | a77b8c9 | 2020-12-21 14:45:50 +0530 | [diff] [blame] | 180 | |
rohitwaghchaure | 31fe5f5 | 2021-08-02 11:01:30 +0530 | [diff] [blame] | 181 | i = get_current_index(doc) or 0 |
Nabin Hait | a77b8c9 | 2020-12-21 14:45:50 +0530 | [diff] [blame] | 182 | while i < len(args): |
rohitwaghchaure | 31fe5f5 | 2021-08-02 11:01:30 +0530 | [diff] [blame] | 183 | validate_item_warehouse(args[i]) |
| 184 | |
Nabin Hait | a77b8c9 | 2020-12-21 14:45:50 +0530 | [diff] [blame] | 185 | obj = update_entries_after({ |
rohitwaghchaure | 31fe5f5 | 2021-08-02 11:01:30 +0530 | [diff] [blame] | 186 | 'item_code': args[i].get('item_code'), |
| 187 | 'warehouse': args[i].get('warehouse'), |
| 188 | 'posting_date': args[i].get('posting_date'), |
| 189 | 'posting_time': args[i].get('posting_time'), |
| 190 | 'creation': args[i].get('creation'), |
| 191 | 'distinct_item_warehouses': distinct_item_warehouses |
Nabin Hait | a77b8c9 | 2020-12-21 14:45:50 +0530 | [diff] [blame] | 192 | }, allow_negative_stock=allow_negative_stock, via_landed_cost_voucher=via_landed_cost_voucher) |
| 193 | |
rohitwaghchaure | 31fe5f5 | 2021-08-02 11:01:30 +0530 | [diff] [blame] | 194 | distinct_item_warehouses[(args[i].get('item_code'), args[i].get('warehouse'))].reposting_status = True |
Deepesh Garg | b4be292 | 2021-01-28 13:09:56 +0530 | [diff] [blame] | 195 | |
Nabin Hait | 97bce3a | 2021-07-12 13:24:43 +0530 | [diff] [blame] | 196 | if obj.new_items_found: |
Ankush Menat | 8fe5feb | 2021-11-04 19:48:32 +0530 | [diff] [blame] | 197 | for item_wh, data in distinct_item_warehouses.items(): |
Nabin Hait | 97bce3a | 2021-07-12 13:24:43 +0530 | [diff] [blame] | 198 | if ('args_idx' not in data and not data.reposting_status) or (data.sle_changed and data.reposting_status): |
| 199 | data.args_idx = len(args) |
| 200 | args.append(data.sle) |
| 201 | elif data.sle_changed and not data.reposting_status: |
| 202 | args[data.args_idx] = data.sle |
rohitwaghchaure | 31fe5f5 | 2021-08-02 11:01:30 +0530 | [diff] [blame] | 203 | |
Nabin Hait | 97bce3a | 2021-07-12 13:24:43 +0530 | [diff] [blame] | 204 | data.sle_changed = False |
Nabin Hait | a77b8c9 | 2020-12-21 14:45:50 +0530 | [diff] [blame] | 205 | i += 1 |
| 206 | |
rohitwaghchaure | 31fe5f5 | 2021-08-02 11:01:30 +0530 | [diff] [blame] | 207 | if doc and i % 2 == 0: |
| 208 | update_args_in_repost_item_valuation(doc, i, args, distinct_item_warehouses) |
| 209 | |
| 210 | if doc and args: |
| 211 | update_args_in_repost_item_valuation(doc, i, args, distinct_item_warehouses) |
| 212 | |
| 213 | def validate_item_warehouse(args): |
| 214 | for field in ['item_code', 'warehouse', 'posting_date', 'posting_time']: |
| 215 | if not args.get(field): |
| 216 | validation_msg = f'The field {frappe.unscrub(args.get(field))} is required for the reposting' |
| 217 | frappe.throw(_(validation_msg)) |
| 218 | |
| 219 | def update_args_in_repost_item_valuation(doc, index, args, distinct_item_warehouses): |
| 220 | frappe.db.set_value(doc.doctype, doc.name, { |
| 221 | 'items_to_be_repost': json.dumps(args, default=str), |
| 222 | 'distinct_item_and_warehouse': json.dumps({str(k): v for k,v in distinct_item_warehouses.items()}, default=str), |
| 223 | 'current_index': index |
| 224 | }) |
| 225 | |
| 226 | frappe.db.commit() |
| 227 | |
| 228 | frappe.publish_realtime('item_reposting_progress', { |
| 229 | 'name': doc.name, |
| 230 | 'items_to_be_repost': json.dumps(args, default=str), |
| 231 | 'current_index': index |
| 232 | }) |
| 233 | |
| 234 | def get_items_to_be_repost(voucher_type, voucher_no, doc=None): |
| 235 | if doc and doc.items_to_be_repost: |
| 236 | return json.loads(doc.items_to_be_repost) or [] |
| 237 | |
Nabin Hait | a77b8c9 | 2020-12-21 14:45:50 +0530 | [diff] [blame] | 238 | return frappe.db.get_all("Stock Ledger Entry", |
| 239 | filters={"voucher_type": voucher_type, "voucher_no": voucher_no}, |
Nabin Hait | 186a045 | 2021-02-18 14:14:21 +0530 | [diff] [blame] | 240 | fields=["item_code", "warehouse", "posting_date", "posting_time", "creation"], |
Nabin Hait | a77b8c9 | 2020-12-21 14:45:50 +0530 | [diff] [blame] | 241 | order_by="creation asc", |
| 242 | group_by="item_code, warehouse" |
| 243 | ) |
Nabin Hait | 74c281c | 2013-08-19 16:17:18 +0530 | [diff] [blame] | 244 | |
rohitwaghchaure | 31fe5f5 | 2021-08-02 11:01:30 +0530 | [diff] [blame] | 245 | def get_distinct_item_warehouse(args=None, doc=None): |
| 246 | distinct_item_warehouses = {} |
| 247 | if doc and doc.distinct_item_and_warehouse: |
| 248 | distinct_item_warehouses = json.loads(doc.distinct_item_and_warehouse) |
| 249 | distinct_item_warehouses = {frappe.safe_eval(k): frappe._dict(v) for k, v in distinct_item_warehouses.items()} |
| 250 | else: |
| 251 | for i, d in enumerate(args): |
| 252 | distinct_item_warehouses.setdefault((d.item_code, d.warehouse), frappe._dict({ |
| 253 | "reposting_status": False, |
| 254 | "sle": d, |
| 255 | "args_idx": i |
| 256 | })) |
| 257 | |
| 258 | return distinct_item_warehouses |
| 259 | |
| 260 | def get_current_index(doc=None): |
| 261 | if doc and doc.current_index: |
| 262 | return doc.current_index |
| 263 | |
Rushabh Mehta | df9e80c | 2015-02-17 19:55:17 +0530 | [diff] [blame] | 264 | class update_entries_after(object): |
Nabin Hait | 902e860 | 2013-01-08 18:29:24 +0530 | [diff] [blame] | 265 | """ |
Nabin Hait | dc82d4f | 2014-04-07 12:02:57 +0530 | [diff] [blame] | 266 | update valution rate and qty after transaction |
Nabin Hait | 902e860 | 2013-01-08 18:29:24 +0530 | [diff] [blame] | 267 | from the current time-bucket onwards |
Nabin Hait | dc82d4f | 2014-04-07 12:02:57 +0530 | [diff] [blame] | 268 | |
Rushabh Mehta | df9e80c | 2015-02-17 19:55:17 +0530 | [diff] [blame] | 269 | :param args: args as dict |
| 270 | |
| 271 | args = { |
| 272 | "item_code": "ABC", |
| 273 | "warehouse": "XYZ", |
| 274 | "posting_date": "2012-12-12", |
| 275 | "posting_time": "12:00" |
| 276 | } |
Nabin Hait | 902e860 | 2013-01-08 18:29:24 +0530 | [diff] [blame] | 277 | """ |
Anand Doshi | 0dc79f4 | 2015-04-06 12:59:34 +0530 | [diff] [blame] | 278 | def __init__(self, args, allow_zero_rate=False, allow_negative_stock=None, via_landed_cost_voucher=False, verbose=1): |
Nabin Hait | a77b8c9 | 2020-12-21 14:45:50 +0530 | [diff] [blame] | 279 | self.exceptions = {} |
Rushabh Mehta | df9e80c | 2015-02-17 19:55:17 +0530 | [diff] [blame] | 280 | self.verbose = verbose |
| 281 | self.allow_zero_rate = allow_zero_rate |
Anand Doshi | 0dc79f4 | 2015-04-06 12:59:34 +0530 | [diff] [blame] | 282 | self.via_landed_cost_voucher = via_landed_cost_voucher |
Ankush Menat | eb8b424 | 2022-02-12 13:08:28 +0530 | [diff] [blame] | 283 | self.item_code = args.get("item_code") |
| 284 | self.allow_negative_stock = allow_negative_stock or is_negative_stock_allowed(item_code=self.item_code) |
Nabin Hait | dc82d4f | 2014-04-07 12:02:57 +0530 | [diff] [blame] | 285 | |
Nabin Hait | a77b8c9 | 2020-12-21 14:45:50 +0530 | [diff] [blame] | 286 | self.args = frappe._dict(args) |
Nabin Hait | a77b8c9 | 2020-12-21 14:45:50 +0530 | [diff] [blame] | 287 | if self.args.sle_id: |
| 288 | self.args['name'] = self.args.sle_id |
Nabin Hait | d46b236 | 2021-02-23 16:38:52 +0530 | [diff] [blame] | 289 | |
Nabin Hait | a77b8c9 | 2020-12-21 14:45:50 +0530 | [diff] [blame] | 290 | self.company = frappe.get_cached_value("Warehouse", self.args.warehouse, "company") |
| 291 | self.get_precision() |
| 292 | self.valuation_method = get_valuation_method(self.item_code) |
Nabin Hait | 97bce3a | 2021-07-12 13:24:43 +0530 | [diff] [blame] | 293 | |
| 294 | self.new_items_found = False |
| 295 | self.distinct_item_warehouses = args.get("distinct_item_warehouses", frappe._dict()) |
Nabin Hait | a77b8c9 | 2020-12-21 14:45:50 +0530 | [diff] [blame] | 296 | |
| 297 | self.data = frappe._dict() |
| 298 | self.initialize_previous_data(self.args) |
Nabin Hait | a77b8c9 | 2020-12-21 14:45:50 +0530 | [diff] [blame] | 299 | self.build() |
Deepesh Garg | b4be292 | 2021-01-28 13:09:56 +0530 | [diff] [blame] | 300 | |
Nabin Hait | a77b8c9 | 2020-12-21 14:45:50 +0530 | [diff] [blame] | 301 | def get_precision(self): |
| 302 | company_base_currency = frappe.get_cached_value('Company', self.company, "default_currency") |
| 303 | self.precision = get_field_precision(frappe.get_meta("Stock Ledger Entry").get_field("stock_value"), |
| 304 | currency=company_base_currency) |
| 305 | |
| 306 | def initialize_previous_data(self, args): |
| 307 | """ |
| 308 | Get previous sl entries for current item for each related warehouse |
| 309 | and assigns into self.data dict |
| 310 | |
| 311 | :Data Structure: |
| 312 | |
| 313 | self.data = { |
| 314 | warehouse1: { |
| 315 | 'previus_sle': {}, |
| 316 | 'qty_after_transaction': 10, |
| 317 | 'valuation_rate': 100, |
| 318 | 'stock_value': 1000, |
| 319 | 'prev_stock_value': 1000, |
| 320 | 'stock_queue': '[[10, 100]]', |
| 321 | 'stock_value_difference': 1000 |
| 322 | } |
| 323 | } |
| 324 | |
| 325 | """ |
Ankush Menat | c1d986a | 2021-08-31 19:43:42 +0530 | [diff] [blame] | 326 | self.data.setdefault(args.warehouse, frappe._dict()) |
| 327 | warehouse_dict = self.data[args.warehouse] |
marination | 8418c4b | 2021-06-22 21:35:25 +0530 | [diff] [blame] | 328 | previous_sle = get_previous_sle_of_current_voucher(args) |
Ankush Menat | c1d986a | 2021-08-31 19:43:42 +0530 | [diff] [blame] | 329 | warehouse_dict.previous_sle = previous_sle |
Nabin Hait | bb77756 | 2013-08-29 18:19:37 +0530 | [diff] [blame] | 330 | |
Ankush Menat | c1d986a | 2021-08-31 19:43:42 +0530 | [diff] [blame] | 331 | for key in ("qty_after_transaction", "valuation_rate", "stock_value"): |
| 332 | setattr(warehouse_dict, key, flt(previous_sle.get(key))) |
| 333 | |
| 334 | warehouse_dict.update({ |
Nabin Hait | a77b8c9 | 2020-12-21 14:45:50 +0530 | [diff] [blame] | 335 | "prev_stock_value": previous_sle.stock_value or 0.0, |
| 336 | "stock_queue": json.loads(previous_sle.stock_queue or "[]"), |
| 337 | "stock_value_difference": 0.0 |
| 338 | }) |
Rushabh Mehta | df9e80c | 2015-02-17 19:55:17 +0530 | [diff] [blame] | 339 | |
Nabin Hait | a77b8c9 | 2020-12-21 14:45:50 +0530 | [diff] [blame] | 340 | def build(self): |
Sagar Vora | e50324a | 2021-03-31 12:44:03 +0530 | [diff] [blame] | 341 | from erpnext.controllers.stock_controller import future_sle_exists |
Nabin Hait | 186a045 | 2021-02-18 14:14:21 +0530 | [diff] [blame] | 342 | |
Nabin Hait | a77b8c9 | 2020-12-21 14:45:50 +0530 | [diff] [blame] | 343 | if self.args.get("sle_id"): |
Nabin Hait | 186a045 | 2021-02-18 14:14:21 +0530 | [diff] [blame] | 344 | self.process_sle_against_current_timestamp() |
Sagar Vora | e50324a | 2021-03-31 12:44:03 +0530 | [diff] [blame] | 345 | if not future_sle_exists(self.args): |
Nabin Hait | 186a045 | 2021-02-18 14:14:21 +0530 | [diff] [blame] | 346 | self.update_bin() |
Deepesh Garg | 2a9c5ba | 2020-04-30 10:38:58 +0530 | [diff] [blame] | 347 | else: |
Nabin Hait | a77b8c9 | 2020-12-21 14:45:50 +0530 | [diff] [blame] | 348 | entries_to_fix = self.get_future_entries_to_fix() |
| 349 | |
| 350 | i = 0 |
| 351 | while i < len(entries_to_fix): |
| 352 | sle = entries_to_fix[i] |
| 353 | i += 1 |
| 354 | |
Deepesh Garg | 2a9c5ba | 2020-04-30 10:38:58 +0530 | [diff] [blame] | 355 | self.process_sle(sle) |
Rushabh Mehta | df9e80c | 2015-02-17 19:55:17 +0530 | [diff] [blame] | 356 | |
Nabin Hait | a77b8c9 | 2020-12-21 14:45:50 +0530 | [diff] [blame] | 357 | if sle.dependant_sle_voucher_detail_no: |
Nabin Hait | 243d59b | 2021-02-02 16:55:13 +0530 | [diff] [blame] | 358 | entries_to_fix = self.get_dependent_entries_to_fix(entries_to_fix, sle) |
Nabin Hait | d46b236 | 2021-02-23 16:38:52 +0530 | [diff] [blame] | 359 | |
Nabin Hait | 186a045 | 2021-02-18 14:14:21 +0530 | [diff] [blame] | 360 | self.update_bin() |
Nabin Hait | a77b8c9 | 2020-12-21 14:45:50 +0530 | [diff] [blame] | 361 | |
Rushabh Mehta | df9e80c | 2015-02-17 19:55:17 +0530 | [diff] [blame] | 362 | if self.exceptions: |
| 363 | self.raise_exceptions() |
| 364 | |
Nabin Hait | 186a045 | 2021-02-18 14:14:21 +0530 | [diff] [blame] | 365 | def process_sle_against_current_timestamp(self): |
Nabin Hait | a77b8c9 | 2020-12-21 14:45:50 +0530 | [diff] [blame] | 366 | sl_entries = self.get_sle_against_current_voucher() |
| 367 | for sle in sl_entries: |
| 368 | self.process_sle(sle) |
Rushabh Mehta | df9e80c | 2015-02-17 19:55:17 +0530 | [diff] [blame] | 369 | |
Nabin Hait | a77b8c9 | 2020-12-21 14:45:50 +0530 | [diff] [blame] | 370 | def get_sle_against_current_voucher(self): |
Nabin Hait | f2be080 | 2021-02-15 19:27:49 +0530 | [diff] [blame] | 371 | self.args['time_format'] = '%H:%i:%s' |
| 372 | |
Nabin Hait | a77b8c9 | 2020-12-21 14:45:50 +0530 | [diff] [blame] | 373 | return frappe.db.sql(""" |
| 374 | select |
| 375 | *, timestamp(posting_date, posting_time) as "timestamp" |
| 376 | from |
| 377 | `tabStock Ledger Entry` |
| 378 | where |
| 379 | item_code = %(item_code)s |
| 380 | and warehouse = %(warehouse)s |
rohitwaghchaure | fe4540d | 2021-08-26 12:52:36 +0530 | [diff] [blame] | 381 | and is_cancelled = 0 |
Nabin Hait | 186a045 | 2021-02-18 14:14:21 +0530 | [diff] [blame] | 382 | and timestamp(posting_date, time_format(posting_time, %(time_format)s)) = timestamp(%(posting_date)s, time_format(%(posting_time)s, %(time_format)s)) |
| 383 | |
Nabin Hait | a77b8c9 | 2020-12-21 14:45:50 +0530 | [diff] [blame] | 384 | order by |
| 385 | creation ASC |
| 386 | for update |
| 387 | """, self.args, as_dict=1) |
Rushabh Mehta | df9e80c | 2015-02-17 19:55:17 +0530 | [diff] [blame] | 388 | |
Nabin Hait | a77b8c9 | 2020-12-21 14:45:50 +0530 | [diff] [blame] | 389 | def get_future_entries_to_fix(self): |
| 390 | # includes current entry! |
| 391 | args = self.data[self.args.warehouse].previous_sle \ |
| 392 | or frappe._dict({"item_code": self.item_code, "warehouse": self.args.warehouse}) |
Deepesh Garg | b4be292 | 2021-01-28 13:09:56 +0530 | [diff] [blame] | 393 | |
Nabin Hait | a77b8c9 | 2020-12-21 14:45:50 +0530 | [diff] [blame] | 394 | return list(self.get_sle_after_datetime(args)) |
Rushabh Mehta | 538607e | 2016-06-12 11:03:00 +0530 | [diff] [blame] | 395 | |
Nabin Hait | a77b8c9 | 2020-12-21 14:45:50 +0530 | [diff] [blame] | 396 | def get_dependent_entries_to_fix(self, entries_to_fix, sle): |
| 397 | dependant_sle = get_sle_by_voucher_detail_no(sle.dependant_sle_voucher_detail_no, |
| 398 | excluded_sle=sle.name) |
Deepesh Garg | b4be292 | 2021-01-28 13:09:56 +0530 | [diff] [blame] | 399 | |
Nabin Hait | a77b8c9 | 2020-12-21 14:45:50 +0530 | [diff] [blame] | 400 | if not dependant_sle: |
Nabin Hait | 243d59b | 2021-02-02 16:55:13 +0530 | [diff] [blame] | 401 | return entries_to_fix |
Nabin Hait | a77b8c9 | 2020-12-21 14:45:50 +0530 | [diff] [blame] | 402 | elif dependant_sle.item_code == self.item_code and dependant_sle.warehouse == self.args.warehouse: |
Nabin Hait | 243d59b | 2021-02-02 16:55:13 +0530 | [diff] [blame] | 403 | return entries_to_fix |
| 404 | elif dependant_sle.item_code != self.item_code: |
Nabin Hait | 97bce3a | 2021-07-12 13:24:43 +0530 | [diff] [blame] | 405 | self.update_distinct_item_warehouses(dependant_sle) |
Nabin Hait | 243d59b | 2021-02-02 16:55:13 +0530 | [diff] [blame] | 406 | return entries_to_fix |
| 407 | elif dependant_sle.item_code == self.item_code and dependant_sle.warehouse in self.data: |
| 408 | return entries_to_fix |
Nabin Hait | 97bce3a | 2021-07-12 13:24:43 +0530 | [diff] [blame] | 409 | else: |
| 410 | return self.append_future_sle_for_dependant(dependant_sle, entries_to_fix) |
| 411 | |
| 412 | def update_distinct_item_warehouses(self, dependant_sle): |
| 413 | key = (dependant_sle.item_code, dependant_sle.warehouse) |
| 414 | val = frappe._dict({ |
| 415 | "sle": dependant_sle |
| 416 | }) |
| 417 | if key not in self.distinct_item_warehouses: |
| 418 | self.distinct_item_warehouses[key] = val |
| 419 | self.new_items_found = True |
| 420 | else: |
| 421 | existing_sle_posting_date = self.distinct_item_warehouses[key].get("sle", {}).get("posting_date") |
| 422 | if getdate(dependant_sle.posting_date) < getdate(existing_sle_posting_date): |
| 423 | val.sle_changed = True |
| 424 | self.distinct_item_warehouses[key] = val |
| 425 | self.new_items_found = True |
| 426 | |
| 427 | def append_future_sle_for_dependant(self, dependant_sle, entries_to_fix): |
Nabin Hait | a77b8c9 | 2020-12-21 14:45:50 +0530 | [diff] [blame] | 428 | self.initialize_previous_data(dependant_sle) |
| 429 | |
| 430 | args = self.data[dependant_sle.warehouse].previous_sle \ |
| 431 | or frappe._dict({"item_code": self.item_code, "warehouse": dependant_sle.warehouse}) |
| 432 | future_sle_for_dependant = list(self.get_sle_after_datetime(args)) |
| 433 | |
| 434 | entries_to_fix.extend(future_sle_for_dependant) |
Nabin Hait | 243d59b | 2021-02-02 16:55:13 +0530 | [diff] [blame] | 435 | return sorted(entries_to_fix, key=lambda k: k['timestamp']) |
Rushabh Mehta | df9e80c | 2015-02-17 19:55:17 +0530 | [diff] [blame] | 436 | |
| 437 | def process_sle(self, sle): |
Ankush Menat | 66bf21f | 2022-01-16 20:45:59 +0530 | [diff] [blame] | 438 | from erpnext.stock.doctype.serial_no.serial_no import get_serial_nos |
| 439 | |
Nabin Hait | a77b8c9 | 2020-12-21 14:45:50 +0530 | [diff] [blame] | 440 | # previous sle data for this warehouse |
| 441 | self.wh_data = self.data[sle.warehouse] |
| 442 | |
Anand Doshi | 0dc79f4 | 2015-04-06 12:59:34 +0530 | [diff] [blame] | 443 | if (sle.serial_no and not self.via_landed_cost_voucher) or not cint(self.allow_negative_stock): |
Nabin Hait | dc82d4f | 2014-04-07 12:02:57 +0530 | [diff] [blame] | 444 | # validate negative stock for serialized items, fifo valuation |
Nabin Hait | 902e860 | 2013-01-08 18:29:24 +0530 | [diff] [blame] | 445 | # or when negative stock is not allowed for moving average |
Rushabh Mehta | df9e80c | 2015-02-17 19:55:17 +0530 | [diff] [blame] | 446 | if not self.validate_negative_stock(sle): |
Nabin Hait | a77b8c9 | 2020-12-21 14:45:50 +0530 | [diff] [blame] | 447 | self.wh_data.qty_after_transaction += flt(sle.actual_qty) |
Rushabh Mehta | df9e80c | 2015-02-17 19:55:17 +0530 | [diff] [blame] | 448 | return |
Nabin Hait | b96c014 | 2014-10-07 11:25:04 +0530 | [diff] [blame] | 449 | |
Nabin Hait | a77b8c9 | 2020-12-21 14:45:50 +0530 | [diff] [blame] | 450 | # Get dynamic incoming/outgoing rate |
Ankush Menat | 701878f | 2022-03-01 18:08:29 +0530 | [diff] [blame] | 451 | if not self.args.get("sle_id"): |
| 452 | self.get_dynamic_incoming_outgoing_rate(sle) |
Deepesh Garg | b4be292 | 2021-01-28 13:09:56 +0530 | [diff] [blame] | 453 | |
Ankush Menat | 66bf21f | 2022-01-16 20:45:59 +0530 | [diff] [blame] | 454 | if get_serial_nos(sle.serial_no): |
Rushabh Mehta | 2a21bc9 | 2015-02-25 15:08:42 +0530 | [diff] [blame] | 455 | self.get_serialized_values(sle) |
Nabin Hait | a77b8c9 | 2020-12-21 14:45:50 +0530 | [diff] [blame] | 456 | self.wh_data.qty_after_transaction += flt(sle.actual_qty) |
Rohit Waghchaure | 05d3bcb | 2019-04-28 18:39:18 +0530 | [diff] [blame] | 457 | if sle.voucher_type == "Stock Reconciliation": |
Nabin Hait | a77b8c9 | 2020-12-21 14:45:50 +0530 | [diff] [blame] | 458 | self.wh_data.qty_after_transaction = sle.qty_after_transaction |
Rohit Waghchaure | 05d3bcb | 2019-04-28 18:39:18 +0530 | [diff] [blame] | 459 | |
Nabin Hait | a77b8c9 | 2020-12-21 14:45:50 +0530 | [diff] [blame] | 460 | self.wh_data.stock_value = flt(self.wh_data.qty_after_transaction) * flt(self.wh_data.valuation_rate) |
Ankush Menat | ce0514c | 2022-02-15 11:41:41 +0530 | [diff] [blame] | 461 | elif sle.batch_no and frappe.db.get_value("Batch", sle.batch_no, "use_batchwise_valuation", cache=True): |
| 462 | self.update_batched_values(sle) |
Nabin Hait | b96c014 | 2014-10-07 11:25:04 +0530 | [diff] [blame] | 463 | else: |
Rohit Waghchaure | 66aa37f | 2019-05-24 16:53:51 +0530 | [diff] [blame] | 464 | if sle.voucher_type=="Stock Reconciliation" and not sle.batch_no: |
Rushabh Mehta | df9e80c | 2015-02-17 19:55:17 +0530 | [diff] [blame] | 465 | # assert |
Nabin Hait | a77b8c9 | 2020-12-21 14:45:50 +0530 | [diff] [blame] | 466 | self.wh_data.valuation_rate = sle.valuation_rate |
| 467 | self.wh_data.qty_after_transaction = sle.qty_after_transaction |
Nabin Hait | a77b8c9 | 2020-12-21 14:45:50 +0530 | [diff] [blame] | 468 | self.wh_data.stock_value = flt(self.wh_data.qty_after_transaction) * flt(self.wh_data.valuation_rate) |
Ankush Menat | b0cf619 | 2022-01-16 13:02:23 +0530 | [diff] [blame] | 469 | if self.valuation_method != "Moving Average": |
| 470 | self.wh_data.stock_queue = [[self.wh_data.qty_after_transaction, self.wh_data.valuation_rate]] |
Nabin Hait | b96c014 | 2014-10-07 11:25:04 +0530 | [diff] [blame] | 471 | else: |
Rushabh Mehta | df9e80c | 2015-02-17 19:55:17 +0530 | [diff] [blame] | 472 | if self.valuation_method == "Moving Average": |
| 473 | self.get_moving_average_values(sle) |
Nabin Hait | a77b8c9 | 2020-12-21 14:45:50 +0530 | [diff] [blame] | 474 | self.wh_data.qty_after_transaction += flt(sle.actual_qty) |
| 475 | self.wh_data.stock_value = flt(self.wh_data.qty_after_transaction) * flt(self.wh_data.valuation_rate) |
Nabin Hait | b96c014 | 2014-10-07 11:25:04 +0530 | [diff] [blame] | 476 | else: |
Ankush Menat | f089d39 | 2022-02-02 12:51:21 +0530 | [diff] [blame] | 477 | self.update_queue_values(sle) |
Nabin Hait | b96c014 | 2014-10-07 11:25:04 +0530 | [diff] [blame] | 478 | |
Rushabh Mehta | 5404778 | 2013-12-26 11:07:46 +0530 | [diff] [blame] | 479 | # rounding as per precision |
Nabin Hait | a77b8c9 | 2020-12-21 14:45:50 +0530 | [diff] [blame] | 480 | self.wh_data.stock_value = flt(self.wh_data.stock_value, self.precision) |
Ankush Menat | 609d2fc | 2022-02-20 11:35:53 +0530 | [diff] [blame] | 481 | if not self.wh_data.qty_after_transaction: |
| 482 | self.wh_data.stock_value = 0.0 |
Nabin Hait | a77b8c9 | 2020-12-21 14:45:50 +0530 | [diff] [blame] | 483 | stock_value_difference = self.wh_data.stock_value - self.wh_data.prev_stock_value |
| 484 | self.wh_data.prev_stock_value = self.wh_data.stock_value |
Nabin Hait | dc82d4f | 2014-04-07 12:02:57 +0530 | [diff] [blame] | 485 | |
Nabin Hait | 902e860 | 2013-01-08 18:29:24 +0530 | [diff] [blame] | 486 | # update current sle |
Nabin Hait | a77b8c9 | 2020-12-21 14:45:50 +0530 | [diff] [blame] | 487 | sle.qty_after_transaction = self.wh_data.qty_after_transaction |
| 488 | sle.valuation_rate = self.wh_data.valuation_rate |
| 489 | sle.stock_value = self.wh_data.stock_value |
| 490 | sle.stock_queue = json.dumps(self.wh_data.stock_queue) |
Rushabh Mehta | 2e0e711 | 2015-02-18 11:38:05 +0530 | [diff] [blame] | 491 | sle.stock_value_difference = stock_value_difference |
Rushabh Mehta | 8bb6e53 | 2015-02-18 20:22:59 +0530 | [diff] [blame] | 492 | sle.doctype="Stock Ledger Entry" |
| 493 | frappe.get_doc(sle).db_update() |
Nabin Hait | dc82d4f | 2014-04-07 12:02:57 +0530 | [diff] [blame] | 494 | |
Ankush Menat | 701878f | 2022-03-01 18:08:29 +0530 | [diff] [blame] | 495 | if not self.args.get("sle_id"): |
| 496 | self.update_outgoing_rate_on_transaction(sle) |
Nabin Hait | a77b8c9 | 2020-12-21 14:45:50 +0530 | [diff] [blame] | 497 | |
Ankush Menat | ce0514c | 2022-02-15 11:41:41 +0530 | [diff] [blame] | 498 | |
Rushabh Mehta | df9e80c | 2015-02-17 19:55:17 +0530 | [diff] [blame] | 499 | def validate_negative_stock(self, sle): |
| 500 | """ |
| 501 | validate negative stock for entries current datetime onwards |
| 502 | will not consider cancelled entries |
| 503 | """ |
Nabin Hait | a77b8c9 | 2020-12-21 14:45:50 +0530 | [diff] [blame] | 504 | diff = self.wh_data.qty_after_transaction + flt(sle.actual_qty) |
Nabin Hait | dc82d4f | 2014-04-07 12:02:57 +0530 | [diff] [blame] | 505 | |
Rushabh Mehta | df9e80c | 2015-02-17 19:55:17 +0530 | [diff] [blame] | 506 | if diff < 0 and abs(diff) > 0.0001: |
| 507 | # negative stock! |
| 508 | exc = sle.copy().update({"diff": diff}) |
Nabin Hait | a77b8c9 | 2020-12-21 14:45:50 +0530 | [diff] [blame] | 509 | self.exceptions.setdefault(sle.warehouse, []).append(exc) |
Rushabh Mehta | df9e80c | 2015-02-17 19:55:17 +0530 | [diff] [blame] | 510 | return False |
Nabin Hait | 902e860 | 2013-01-08 18:29:24 +0530 | [diff] [blame] | 511 | else: |
Rushabh Mehta | df9e80c | 2015-02-17 19:55:17 +0530 | [diff] [blame] | 512 | return True |
| 513 | |
Nabin Hait | a77b8c9 | 2020-12-21 14:45:50 +0530 | [diff] [blame] | 514 | def get_dynamic_incoming_outgoing_rate(self, sle): |
| 515 | # Get updated incoming/outgoing rate from transaction |
| 516 | if sle.recalculate_rate: |
| 517 | rate = self.get_incoming_outgoing_rate_from_transaction(sle) |
| 518 | |
| 519 | if flt(sle.actual_qty) >= 0: |
| 520 | sle.incoming_rate = rate |
| 521 | else: |
| 522 | sle.outgoing_rate = rate |
| 523 | |
| 524 | def get_incoming_outgoing_rate_from_transaction(self, sle): |
| 525 | rate = 0 |
| 526 | # Material Transfer, Repack, Manufacturing |
| 527 | if sle.voucher_type == "Stock Entry": |
Nabin Hait | 97bce3a | 2021-07-12 13:24:43 +0530 | [diff] [blame] | 528 | self.recalculate_amounts_in_stock_entry(sle.voucher_no) |
Nabin Hait | a77b8c9 | 2020-12-21 14:45:50 +0530 | [diff] [blame] | 529 | rate = frappe.db.get_value("Stock Entry Detail", sle.voucher_detail_no, "valuation_rate") |
| 530 | # Sales and Purchase Return |
| 531 | elif sle.voucher_type in ("Purchase Receipt", "Purchase Invoice", "Delivery Note", "Sales Invoice"): |
| 532 | if frappe.get_cached_value(sle.voucher_type, sle.voucher_no, "is_return"): |
Chillar Anand | 915b343 | 2021-09-02 16:44:59 +0530 | [diff] [blame] | 533 | from erpnext.controllers.sales_and_purchase_return import ( |
| 534 | get_rate_for_return, # don't move this import to top |
| 535 | ) |
rohitwaghchaure | ce6c3b5 | 2021-04-13 20:55:52 +0530 | [diff] [blame] | 536 | rate = get_rate_for_return(sle.voucher_type, sle.voucher_no, sle.item_code, |
| 537 | voucher_detail_no=sle.voucher_detail_no, sle = sle) |
Nabin Hait | a77b8c9 | 2020-12-21 14:45:50 +0530 | [diff] [blame] | 538 | else: |
| 539 | if sle.voucher_type in ("Purchase Receipt", "Purchase Invoice"): |
Deepesh Garg | b4be292 | 2021-01-28 13:09:56 +0530 | [diff] [blame] | 540 | rate_field = "valuation_rate" |
Nabin Hait | a77b8c9 | 2020-12-21 14:45:50 +0530 | [diff] [blame] | 541 | else: |
| 542 | rate_field = "incoming_rate" |
| 543 | |
| 544 | # check in item table |
| 545 | item_code, incoming_rate = frappe.db.get_value(sle.voucher_type + " Item", |
| 546 | sle.voucher_detail_no, ["item_code", rate_field]) |
| 547 | |
| 548 | if item_code == sle.item_code: |
| 549 | rate = incoming_rate |
| 550 | else: |
| 551 | if sle.voucher_type in ("Delivery Note", "Sales Invoice"): |
| 552 | ref_doctype = "Packed Item" |
| 553 | else: |
| 554 | ref_doctype = "Purchase Receipt Item Supplied" |
Deepesh Garg | b4be292 | 2021-01-28 13:09:56 +0530 | [diff] [blame] | 555 | |
Nabin Hait | a77b8c9 | 2020-12-21 14:45:50 +0530 | [diff] [blame] | 556 | rate = frappe.db.get_value(ref_doctype, {"parent_detail_docname": sle.voucher_detail_no, |
| 557 | "item_code": sle.item_code}, rate_field) |
| 558 | |
| 559 | return rate |
| 560 | |
| 561 | def update_outgoing_rate_on_transaction(self, sle): |
| 562 | """ |
| 563 | Update outgoing rate in Stock Entry, Delivery Note, Sales Invoice and Sales Return |
| 564 | In case of Stock Entry, also calculate FG Item rate and total incoming/outgoing amount |
| 565 | """ |
| 566 | if sle.actual_qty and sle.voucher_detail_no: |
| 567 | outgoing_rate = abs(flt(sle.stock_value_difference)) / abs(sle.actual_qty) |
| 568 | |
| 569 | if flt(sle.actual_qty) < 0 and sle.voucher_type == "Stock Entry": |
| 570 | self.update_rate_on_stock_entry(sle, outgoing_rate) |
| 571 | elif sle.voucher_type in ("Delivery Note", "Sales Invoice"): |
| 572 | self.update_rate_on_delivery_and_sales_return(sle, outgoing_rate) |
| 573 | elif flt(sle.actual_qty) < 0 and sle.voucher_type in ("Purchase Receipt", "Purchase Invoice"): |
| 574 | self.update_rate_on_purchase_receipt(sle, outgoing_rate) |
| 575 | |
| 576 | def update_rate_on_stock_entry(self, sle, outgoing_rate): |
| 577 | frappe.db.set_value("Stock Entry Detail", sle.voucher_detail_no, "basic_rate", outgoing_rate) |
| 578 | |
Ankush Menat | 701878f | 2022-03-01 18:08:29 +0530 | [diff] [blame] | 579 | # Update outgoing item's rate, recalculate FG Item's rate and total incoming/outgoing amount |
| 580 | if not sle.dependant_sle_voucher_detail_no: |
| 581 | self.recalculate_amounts_in_stock_entry(sle.voucher_no) |
Nabin Hait | 97bce3a | 2021-07-12 13:24:43 +0530 | [diff] [blame] | 582 | |
| 583 | def recalculate_amounts_in_stock_entry(self, voucher_no): |
| 584 | stock_entry = frappe.get_doc("Stock Entry", voucher_no, for_update=True) |
Nabin Hait | a77b8c9 | 2020-12-21 14:45:50 +0530 | [diff] [blame] | 585 | stock_entry.calculate_rate_and_amount(reset_outgoing_rate=False, raise_error_if_no_rate=False) |
| 586 | stock_entry.db_update() |
| 587 | for d in stock_entry.items: |
| 588 | d.db_update() |
Deepesh Garg | b4be292 | 2021-01-28 13:09:56 +0530 | [diff] [blame] | 589 | |
Nabin Hait | a77b8c9 | 2020-12-21 14:45:50 +0530 | [diff] [blame] | 590 | def update_rate_on_delivery_and_sales_return(self, sle, outgoing_rate): |
| 591 | # Update item's incoming rate on transaction |
| 592 | item_code = frappe.db.get_value(sle.voucher_type + " Item", sle.voucher_detail_no, "item_code") |
| 593 | if item_code == sle.item_code: |
| 594 | frappe.db.set_value(sle.voucher_type + " Item", sle.voucher_detail_no, "incoming_rate", outgoing_rate) |
| 595 | else: |
| 596 | # packed item |
| 597 | frappe.db.set_value("Packed Item", |
| 598 | {"parent_detail_docname": sle.voucher_detail_no, "item_code": sle.item_code}, |
| 599 | "incoming_rate", outgoing_rate) |
| 600 | |
| 601 | def update_rate_on_purchase_receipt(self, sle, outgoing_rate): |
| 602 | if frappe.db.exists(sle.voucher_type + " Item", sle.voucher_detail_no): |
| 603 | frappe.db.set_value(sle.voucher_type + " Item", sle.voucher_detail_no, "base_net_rate", outgoing_rate) |
| 604 | else: |
| 605 | frappe.db.set_value("Purchase Receipt Item Supplied", sle.voucher_detail_no, "rate", outgoing_rate) |
| 606 | |
| 607 | # Recalculate subcontracted item's rate in case of subcontracted purchase receipt/invoice |
Rohit Waghchaure | 4d81d45 | 2021-06-15 10:21:44 +0530 | [diff] [blame] | 608 | if frappe.get_cached_value(sle.voucher_type, sle.voucher_no, "is_subcontracted") == 'Yes': |
Rohit Waghchaure | e5fb239 | 2021-06-18 20:37:42 +0530 | [diff] [blame] | 609 | doc = frappe.get_doc(sle.voucher_type, sle.voucher_no) |
Nabin Hait | a77b8c9 | 2020-12-21 14:45:50 +0530 | [diff] [blame] | 610 | doc.update_valuation_rate(reset_outgoing_rate=False) |
| 611 | for d in (doc.items + doc.supplied_items): |
| 612 | d.db_update() |
| 613 | |
Rushabh Mehta | df9e80c | 2015-02-17 19:55:17 +0530 | [diff] [blame] | 614 | def get_serialized_values(self, sle): |
| 615 | incoming_rate = flt(sle.incoming_rate) |
| 616 | actual_qty = flt(sle.actual_qty) |
Nabin Hait | 328c4f9 | 2020-01-02 19:00:32 +0530 | [diff] [blame] | 617 | serial_nos = cstr(sle.serial_no).split("\n") |
Rushabh Mehta | df9e80c | 2015-02-17 19:55:17 +0530 | [diff] [blame] | 618 | |
| 619 | if incoming_rate < 0: |
| 620 | # wrong incoming rate |
Nabin Hait | a77b8c9 | 2020-12-21 14:45:50 +0530 | [diff] [blame] | 621 | incoming_rate = self.wh_data.valuation_rate |
Rushabh Mehta | 538607e | 2016-06-12 11:03:00 +0530 | [diff] [blame] | 622 | |
Nabin Hait | 2620bf4 | 2016-02-29 11:30:27 +0530 | [diff] [blame] | 623 | stock_value_change = 0 |
Ankush Menat | b9642a1 | 2021-12-21 16:49:41 +0530 | [diff] [blame] | 624 | if actual_qty > 0: |
Nabin Hait | 2620bf4 | 2016-02-29 11:30:27 +0530 | [diff] [blame] | 625 | stock_value_change = actual_qty * incoming_rate |
Ankush Menat | b9642a1 | 2021-12-21 16:49:41 +0530 | [diff] [blame] | 626 | else: |
Nabin Hait | 2620bf4 | 2016-02-29 11:30:27 +0530 | [diff] [blame] | 627 | # In case of delivery/stock issue, get average purchase rate |
| 628 | # of serial nos of current entry |
Nabin Hait | a77b8c9 | 2020-12-21 14:45:50 +0530 | [diff] [blame] | 629 | if not sle.is_cancelled: |
| 630 | outgoing_value = self.get_incoming_value_for_serial_nos(sle, serial_nos) |
| 631 | stock_value_change = -1 * outgoing_value |
| 632 | else: |
| 633 | stock_value_change = actual_qty * sle.outgoing_rate |
Rushabh Mehta | 2a21bc9 | 2015-02-25 15:08:42 +0530 | [diff] [blame] | 634 | |
Nabin Hait | a77b8c9 | 2020-12-21 14:45:50 +0530 | [diff] [blame] | 635 | new_stock_qty = self.wh_data.qty_after_transaction + actual_qty |
rohitwaghchaure | 0fe6ced | 2018-07-27 10:33:30 +0530 | [diff] [blame] | 636 | |
Nabin Hait | 2620bf4 | 2016-02-29 11:30:27 +0530 | [diff] [blame] | 637 | if new_stock_qty > 0: |
Nabin Hait | a77b8c9 | 2020-12-21 14:45:50 +0530 | [diff] [blame] | 638 | new_stock_value = (self.wh_data.qty_after_transaction * self.wh_data.valuation_rate) + stock_value_change |
rohitwaghchaure | 0fe6ced | 2018-07-27 10:33:30 +0530 | [diff] [blame] | 639 | if new_stock_value >= 0: |
Nabin Hait | 2620bf4 | 2016-02-29 11:30:27 +0530 | [diff] [blame] | 640 | # calculate new valuation rate only if stock value is positive |
| 641 | # else it remains the same as that of previous entry |
Nabin Hait | a77b8c9 | 2020-12-21 14:45:50 +0530 | [diff] [blame] | 642 | self.wh_data.valuation_rate = new_stock_value / new_stock_qty |
Rushabh Mehta | cca33b2 | 2016-07-08 18:24:46 +0530 | [diff] [blame] | 643 | |
Nabin Hait | a77b8c9 | 2020-12-21 14:45:50 +0530 | [diff] [blame] | 644 | if not self.wh_data.valuation_rate and sle.voucher_detail_no: |
rohitwaghchaure | b1ac979 | 2017-12-01 16:09:02 +0530 | [diff] [blame] | 645 | allow_zero_rate = self.check_if_allow_zero_valuation_rate(sle.voucher_type, sle.voucher_detail_no) |
| 646 | if not allow_zero_rate: |
Ankush Menat | d7ca83e | 2022-02-19 19:35:33 +0530 | [diff] [blame] | 647 | self.wh_data.valuation_rate = self.get_fallback_rate(sle) |
rohitwaghchaure | b1ac979 | 2017-12-01 16:09:02 +0530 | [diff] [blame] | 648 | |
Nabin Hait | 328c4f9 | 2020-01-02 19:00:32 +0530 | [diff] [blame] | 649 | def get_incoming_value_for_serial_nos(self, sle, serial_nos): |
| 650 | # get rate from serial nos within same company |
| 651 | all_serial_nos = frappe.get_all("Serial No", |
| 652 | fields=["purchase_rate", "name", "company"], |
| 653 | filters = {'name': ('in', serial_nos)}) |
| 654 | |
Ankush Menat | 9891780 | 2021-06-11 18:40:22 +0530 | [diff] [blame] | 655 | incoming_values = sum(flt(d.purchase_rate) for d in all_serial_nos if d.company==sle.company) |
Nabin Hait | 328c4f9 | 2020-01-02 19:00:32 +0530 | [diff] [blame] | 656 | |
| 657 | # Get rate for serial nos which has been transferred to other company |
| 658 | invalid_serial_nos = [d.name for d in all_serial_nos if d.company!=sle.company] |
| 659 | for serial_no in invalid_serial_nos: |
| 660 | incoming_rate = frappe.db.sql(""" |
| 661 | select incoming_rate |
| 662 | from `tabStock Ledger Entry` |
| 663 | where |
| 664 | company = %s |
| 665 | and actual_qty > 0 |
Ankush Menat | 82ea958 | 2022-01-16 20:19:04 +0530 | [diff] [blame] | 666 | and is_cancelled = 0 |
Nabin Hait | 328c4f9 | 2020-01-02 19:00:32 +0530 | [diff] [blame] | 667 | and (serial_no = %s |
| 668 | or serial_no like %s |
| 669 | or serial_no like %s |
| 670 | or serial_no like %s |
| 671 | ) |
| 672 | order by posting_date desc |
| 673 | limit 1 |
| 674 | """, (sle.company, serial_no, serial_no+'\n%', '%\n'+serial_no, '%\n'+serial_no+'\n%')) |
| 675 | |
| 676 | incoming_values += flt(incoming_rate[0][0]) if incoming_rate else 0 |
| 677 | |
| 678 | return incoming_values |
| 679 | |
Rushabh Mehta | df9e80c | 2015-02-17 19:55:17 +0530 | [diff] [blame] | 680 | def get_moving_average_values(self, sle): |
Rushabh Mehta | df9e80c | 2015-02-17 19:55:17 +0530 | [diff] [blame] | 681 | actual_qty = flt(sle.actual_qty) |
Nabin Hait | a77b8c9 | 2020-12-21 14:45:50 +0530 | [diff] [blame] | 682 | new_stock_qty = flt(self.wh_data.qty_after_transaction) + actual_qty |
Nabin Hait | 6dfc78b | 2016-06-24 12:28:55 +0530 | [diff] [blame] | 683 | if new_stock_qty >= 0: |
| 684 | if actual_qty > 0: |
Nabin Hait | a77b8c9 | 2020-12-21 14:45:50 +0530 | [diff] [blame] | 685 | if flt(self.wh_data.qty_after_transaction) <= 0: |
| 686 | self.wh_data.valuation_rate = sle.incoming_rate |
Nabin Hait | 6dfc78b | 2016-06-24 12:28:55 +0530 | [diff] [blame] | 687 | else: |
Nabin Hait | a77b8c9 | 2020-12-21 14:45:50 +0530 | [diff] [blame] | 688 | new_stock_value = (self.wh_data.qty_after_transaction * self.wh_data.valuation_rate) + \ |
Nabin Hait | 6dfc78b | 2016-06-24 12:28:55 +0530 | [diff] [blame] | 689 | (actual_qty * sle.incoming_rate) |
Rushabh Mehta | 14a908b | 2015-10-15 12:28:20 +0530 | [diff] [blame] | 690 | |
Nabin Hait | a77b8c9 | 2020-12-21 14:45:50 +0530 | [diff] [blame] | 691 | self.wh_data.valuation_rate = new_stock_value / new_stock_qty |
Rushabh Mehta | 14a908b | 2015-10-15 12:28:20 +0530 | [diff] [blame] | 692 | |
Nabin Hait | 6dfc78b | 2016-06-24 12:28:55 +0530 | [diff] [blame] | 693 | elif sle.outgoing_rate: |
| 694 | if new_stock_qty: |
Nabin Hait | a77b8c9 | 2020-12-21 14:45:50 +0530 | [diff] [blame] | 695 | new_stock_value = (self.wh_data.qty_after_transaction * self.wh_data.valuation_rate) + \ |
Nabin Hait | 6dfc78b | 2016-06-24 12:28:55 +0530 | [diff] [blame] | 696 | (actual_qty * sle.outgoing_rate) |
Rushabh Mehta | df9e80c | 2015-02-17 19:55:17 +0530 | [diff] [blame] | 697 | |
Nabin Hait | a77b8c9 | 2020-12-21 14:45:50 +0530 | [diff] [blame] | 698 | self.wh_data.valuation_rate = new_stock_value / new_stock_qty |
Nabin Hait | 6dfc78b | 2016-06-24 12:28:55 +0530 | [diff] [blame] | 699 | else: |
Nabin Hait | a77b8c9 | 2020-12-21 14:45:50 +0530 | [diff] [blame] | 700 | self.wh_data.valuation_rate = sle.outgoing_rate |
Nabin Hait | 6dfc78b | 2016-06-24 12:28:55 +0530 | [diff] [blame] | 701 | else: |
Nabin Hait | a77b8c9 | 2020-12-21 14:45:50 +0530 | [diff] [blame] | 702 | if flt(self.wh_data.qty_after_transaction) >= 0 and sle.outgoing_rate: |
| 703 | self.wh_data.valuation_rate = sle.outgoing_rate |
Rushabh Mehta | 14a908b | 2015-10-15 12:28:20 +0530 | [diff] [blame] | 704 | |
Nabin Hait | a77b8c9 | 2020-12-21 14:45:50 +0530 | [diff] [blame] | 705 | if not self.wh_data.valuation_rate and actual_qty > 0: |
| 706 | self.wh_data.valuation_rate = sle.incoming_rate |
Rushabh Mehta | cc8b2b2 | 2017-03-31 12:44:29 +0530 | [diff] [blame] | 707 | |
Rushabh Mehta | aedaac6 | 2017-05-04 09:35:19 +0530 | [diff] [blame] | 708 | # Get valuation rate from previous SLE or Item master, if item does not have the |
Javier Wong | 9b11d9b | 2017-04-14 18:24:04 +0800 | [diff] [blame] | 709 | # allow zero valuration rate flag set |
Nabin Hait | a77b8c9 | 2020-12-21 14:45:50 +0530 | [diff] [blame] | 710 | if not self.wh_data.valuation_rate and sle.voucher_detail_no: |
Javier Wong | 9b11d9b | 2017-04-14 18:24:04 +0800 | [diff] [blame] | 711 | allow_zero_valuation_rate = self.check_if_allow_zero_valuation_rate(sle.voucher_type, sle.voucher_detail_no) |
| 712 | if not allow_zero_valuation_rate: |
Ankush Menat | d7ca83e | 2022-02-19 19:35:33 +0530 | [diff] [blame] | 713 | self.wh_data.valuation_rate = self.get_fallback_rate(sle) |
Rushabh Mehta | cc8b2b2 | 2017-03-31 12:44:29 +0530 | [diff] [blame] | 714 | |
Ankush Menat | f089d39 | 2022-02-02 12:51:21 +0530 | [diff] [blame] | 715 | def update_queue_values(self, sle): |
Rushabh Mehta | df9e80c | 2015-02-17 19:55:17 +0530 | [diff] [blame] | 716 | incoming_rate = flt(sle.incoming_rate) |
| 717 | actual_qty = flt(sle.actual_qty) |
Nabin Hait | ada485f | 2015-07-17 15:09:56 +0530 | [diff] [blame] | 718 | outgoing_rate = flt(sle.outgoing_rate) |
Rushabh Mehta | df9e80c | 2015-02-17 19:55:17 +0530 | [diff] [blame] | 719 | |
Ankush Menat | b534fee | 2022-02-19 20:58:36 +0530 | [diff] [blame] | 720 | self.wh_data.qty_after_transaction = round_off_if_near_zero(self.wh_data.qty_after_transaction + actual_qty) |
| 721 | |
Ankush Menat | 97e18a1 | 2022-01-15 17:42:25 +0530 | [diff] [blame] | 722 | if self.valuation_method == "LIFO": |
| 723 | stock_queue = LIFOValuation(self.wh_data.stock_queue) |
| 724 | else: |
| 725 | stock_queue = FIFOValuation(self.wh_data.stock_queue) |
| 726 | |
Ankush Menat | b534fee | 2022-02-19 20:58:36 +0530 | [diff] [blame] | 727 | _prev_qty, prev_stock_value = stock_queue.get_total_stock_and_value() |
| 728 | |
Rushabh Mehta | df9e80c | 2015-02-17 19:55:17 +0530 | [diff] [blame] | 729 | if actual_qty > 0: |
Ankush Menat | 97e18a1 | 2022-01-15 17:42:25 +0530 | [diff] [blame] | 730 | stock_queue.add_stock(qty=actual_qty, rate=incoming_rate) |
Rushabh Mehta | df9e80c | 2015-02-17 19:55:17 +0530 | [diff] [blame] | 731 | else: |
Ankush Menat | 4b29fb6 | 2021-12-18 18:40:22 +0530 | [diff] [blame] | 732 | def rate_generator() -> float: |
| 733 | allow_zero_valuation_rate = self.check_if_allow_zero_valuation_rate(sle.voucher_type, sle.voucher_detail_no) |
| 734 | if not allow_zero_valuation_rate: |
Ankush Menat | d7ca83e | 2022-02-19 19:35:33 +0530 | [diff] [blame] | 735 | return self.get_fallback_rate(sle) |
Nabin Hait | ada485f | 2015-07-17 15:09:56 +0530 | [diff] [blame] | 736 | else: |
Ankush Menat | 4b29fb6 | 2021-12-18 18:40:22 +0530 | [diff] [blame] | 737 | return 0.0 |
Rushabh Mehta | cca33b2 | 2016-07-08 18:24:46 +0530 | [diff] [blame] | 738 | |
Ankush Menat | 97e18a1 | 2022-01-15 17:42:25 +0530 | [diff] [blame] | 739 | stock_queue.remove_stock(qty=abs(actual_qty), outgoing_rate=outgoing_rate, rate_generator=rate_generator) |
Nabin Hait | dc82d4f | 2014-04-07 12:02:57 +0530 | [diff] [blame] | 740 | |
Ankush Menat | b534fee | 2022-02-19 20:58:36 +0530 | [diff] [blame] | 741 | _qty, stock_value = stock_queue.get_total_stock_and_value() |
| 742 | |
| 743 | stock_value_difference = stock_value - prev_stock_value |
Nabin Hait | dc82d4f | 2014-04-07 12:02:57 +0530 | [diff] [blame] | 744 | |
Ankush Menat | 97e18a1 | 2022-01-15 17:42:25 +0530 | [diff] [blame] | 745 | self.wh_data.stock_queue = stock_queue.state |
Ankush Menat | b534fee | 2022-02-19 20:58:36 +0530 | [diff] [blame] | 746 | self.wh_data.stock_value = round_off_if_near_zero(self.wh_data.stock_value + stock_value_difference) |
Rushabh Mehta | cca33b2 | 2016-07-08 18:24:46 +0530 | [diff] [blame] | 747 | |
Nabin Hait | a77b8c9 | 2020-12-21 14:45:50 +0530 | [diff] [blame] | 748 | if not self.wh_data.stock_queue: |
| 749 | self.wh_data.stock_queue.append([0, sle.incoming_rate or sle.outgoing_rate or self.wh_data.valuation_rate]) |
Rushabh Mehta | cc8b2b2 | 2017-03-31 12:44:29 +0530 | [diff] [blame] | 750 | |
Ankush Menat | b534fee | 2022-02-19 20:58:36 +0530 | [diff] [blame] | 751 | if self.wh_data.qty_after_transaction: |
| 752 | self.wh_data.valuation_rate = self.wh_data.stock_value / self.wh_data.qty_after_transaction |
| 753 | |
Ankush Menat | ce0514c | 2022-02-15 11:41:41 +0530 | [diff] [blame] | 754 | def update_batched_values(self, sle): |
| 755 | incoming_rate = flt(sle.incoming_rate) |
| 756 | actual_qty = flt(sle.actual_qty) |
Ankush Menat | 4b29fb6 | 2021-12-18 18:40:22 +0530 | [diff] [blame] | 757 | |
Ankush Menat | 3548324 | 2022-02-19 22:22:27 +0530 | [diff] [blame] | 758 | self.wh_data.qty_after_transaction = round_off_if_near_zero(self.wh_data.qty_after_transaction + actual_qty) |
Ankush Menat | ce0514c | 2022-02-15 11:41:41 +0530 | [diff] [blame] | 759 | |
| 760 | if actual_qty > 0: |
| 761 | stock_value_difference = incoming_rate * actual_qty |
Ankush Menat | ce0514c | 2022-02-15 11:41:41 +0530 | [diff] [blame] | 762 | else: |
Ankush Menat | 3548324 | 2022-02-19 22:22:27 +0530 | [diff] [blame] | 763 | outgoing_rate = get_batch_incoming_rate(item_code=sle.item_code, |
| 764 | warehouse=sle.warehouse, batch_no=sle.batch_no, posting_date=sle.posting_date, |
| 765 | posting_time=sle.posting_time, creation=sle.creation) |
Ankush Menat | aba7a7c | 2022-02-19 19:36:28 +0530 | [diff] [blame] | 766 | if outgoing_rate is None: |
| 767 | # This can *only* happen if qty available for the batch is zero. |
| 768 | # in such case fall back various other rates. |
| 769 | # future entries will correct the overall accounting as each |
| 770 | # batch individually uses moving average rates. |
| 771 | outgoing_rate = self.get_fallback_rate(sle) |
Ankush Menat | ce0514c | 2022-02-15 11:41:41 +0530 | [diff] [blame] | 772 | stock_value_difference = outgoing_rate * actual_qty |
Ankush Menat | ce0514c | 2022-02-15 11:41:41 +0530 | [diff] [blame] | 773 | |
Ankush Menat | 3548324 | 2022-02-19 22:22:27 +0530 | [diff] [blame] | 774 | self.wh_data.stock_value = round_off_if_near_zero(self.wh_data.stock_value + stock_value_difference) |
Ankush Menat | ce0514c | 2022-02-15 11:41:41 +0530 | [diff] [blame] | 775 | if self.wh_data.qty_after_transaction: |
| 776 | self.wh_data.valuation_rate = self.wh_data.stock_value / self.wh_data.qty_after_transaction |
Ankush Menat | 4b29fb6 | 2021-12-18 18:40:22 +0530 | [diff] [blame] | 777 | |
Javier Wong | 9b11d9b | 2017-04-14 18:24:04 +0800 | [diff] [blame] | 778 | def check_if_allow_zero_valuation_rate(self, voucher_type, voucher_detail_no): |
deepeshgarg007 | f9c0ef3 | 2019-07-30 18:49:19 +0530 | [diff] [blame] | 779 | ref_item_dt = "" |
| 780 | |
| 781 | if voucher_type == "Stock Entry": |
| 782 | ref_item_dt = voucher_type + " Detail" |
| 783 | elif voucher_type in ["Purchase Invoice", "Sales Invoice", "Delivery Note", "Purchase Receipt"]: |
| 784 | ref_item_dt = voucher_type + " Item" |
| 785 | |
| 786 | if ref_item_dt: |
| 787 | return frappe.db.get_value(ref_item_dt, voucher_detail_no, "allow_zero_valuation_rate") |
| 788 | else: |
| 789 | return 0 |
Rushabh Mehta | cc8b2b2 | 2017-03-31 12:44:29 +0530 | [diff] [blame] | 790 | |
Ankush Menat | d7ca83e | 2022-02-19 19:35:33 +0530 | [diff] [blame] | 791 | def get_fallback_rate(self, sle) -> float: |
| 792 | """When exact incoming rate isn't available use any of other "average" rates as fallback. |
| 793 | This should only get used for negative stock.""" |
| 794 | return get_valuation_rate(sle.item_code, sle.warehouse, |
| 795 | sle.voucher_type, sle.voucher_no, self.allow_zero_rate, |
| 796 | currency=erpnext.get_company_currency(sle.company), company=sle.company, batch_no=sle.batch_no) |
| 797 | |
Nabin Hait | a77b8c9 | 2020-12-21 14:45:50 +0530 | [diff] [blame] | 798 | def get_sle_before_datetime(self, args): |
Rushabh Mehta | df9e80c | 2015-02-17 19:55:17 +0530 | [diff] [blame] | 799 | """get previous stock ledger entry before current time-bucket""" |
Nabin Hait | a77b8c9 | 2020-12-21 14:45:50 +0530 | [diff] [blame] | 800 | sle = get_stock_ledger_entries(args, "<", "desc", "limit 1", for_update=False) |
| 801 | sle = sle[0] if sle else frappe._dict() |
| 802 | return sle |
Deepesh Garg | 2a9c5ba | 2020-04-30 10:38:58 +0530 | [diff] [blame] | 803 | |
Nabin Hait | a77b8c9 | 2020-12-21 14:45:50 +0530 | [diff] [blame] | 804 | def get_sle_after_datetime(self, args): |
Rushabh Mehta | df9e80c | 2015-02-17 19:55:17 +0530 | [diff] [blame] | 805 | """get Stock Ledger Entries after a particular datetime, for reposting""" |
Nabin Hait | a77b8c9 | 2020-12-21 14:45:50 +0530 | [diff] [blame] | 806 | return get_stock_ledger_entries(args, ">", "asc", for_update=True, check_serial_no=False) |
Rushabh Mehta | df9e80c | 2015-02-17 19:55:17 +0530 | [diff] [blame] | 807 | |
| 808 | def raise_exceptions(self): |
Nabin Hait | a77b8c9 | 2020-12-21 14:45:50 +0530 | [diff] [blame] | 809 | msg_list = [] |
Ankush Menat | 8fe5feb | 2021-11-04 19:48:32 +0530 | [diff] [blame] | 810 | for warehouse, exceptions in self.exceptions.items(): |
Nabin Hait | a77b8c9 | 2020-12-21 14:45:50 +0530 | [diff] [blame] | 811 | deficiency = min(e["diff"] for e in exceptions) |
Rushabh Mehta | 538607e | 2016-06-12 11:03:00 +0530 | [diff] [blame] | 812 | |
Nabin Hait | a77b8c9 | 2020-12-21 14:45:50 +0530 | [diff] [blame] | 813 | if ((exceptions[0]["voucher_type"], exceptions[0]["voucher_no"]) in |
| 814 | frappe.local.flags.currently_saving): |
Nabin Hait | 3edefb1 | 2016-07-20 16:13:18 +0530 | [diff] [blame] | 815 | |
Nabin Hait | a77b8c9 | 2020-12-21 14:45:50 +0530 | [diff] [blame] | 816 | msg = _("{0} units of {1} needed in {2} to complete this transaction.").format( |
Nabin Hait | 243d59b | 2021-02-02 16:55:13 +0530 | [diff] [blame] | 817 | abs(deficiency), frappe.get_desk_link('Item', exceptions[0]["item_code"]), |
Nabin Hait | a77b8c9 | 2020-12-21 14:45:50 +0530 | [diff] [blame] | 818 | frappe.get_desk_link('Warehouse', warehouse)) |
| 819 | else: |
| 820 | msg = _("{0} units of {1} needed in {2} on {3} {4} for {5} to complete this transaction.").format( |
Nabin Hait | 243d59b | 2021-02-02 16:55:13 +0530 | [diff] [blame] | 821 | abs(deficiency), frappe.get_desk_link('Item', exceptions[0]["item_code"]), |
Nabin Hait | a77b8c9 | 2020-12-21 14:45:50 +0530 | [diff] [blame] | 822 | frappe.get_desk_link('Warehouse', warehouse), |
| 823 | exceptions[0]["posting_date"], exceptions[0]["posting_time"], |
| 824 | frappe.get_desk_link(exceptions[0]["voucher_type"], exceptions[0]["voucher_no"])) |
Rushabh Mehta | 538607e | 2016-06-12 11:03:00 +0530 | [diff] [blame] | 825 | |
Nabin Hait | a77b8c9 | 2020-12-21 14:45:50 +0530 | [diff] [blame] | 826 | if msg: |
| 827 | msg_list.append(msg) |
| 828 | |
| 829 | if msg_list: |
| 830 | message = "\n\n".join(msg_list) |
| 831 | if self.verbose: |
| 832 | frappe.throw(message, NegativeStockError, title='Insufficient Stock') |
| 833 | else: |
| 834 | raise NegativeStockError(message) |
Deepesh Garg | b4be292 | 2021-01-28 13:09:56 +0530 | [diff] [blame] | 835 | |
Nabin Hait | a77b8c9 | 2020-12-21 14:45:50 +0530 | [diff] [blame] | 836 | def update_bin(self): |
| 837 | # update bin for each warehouse |
Ankush Menat | 8fe5feb | 2021-11-04 19:48:32 +0530 | [diff] [blame] | 838 | for warehouse, data in self.data.items(): |
Ankush Menat | 97060c4 | 2021-12-03 11:50:38 +0530 | [diff] [blame] | 839 | bin_name = get_or_make_bin(self.item_code, warehouse) |
Deepesh Garg | 6f107da | 2021-10-12 20:15:55 +0530 | [diff] [blame] | 840 | |
Ankush Menat | 97060c4 | 2021-12-03 11:50:38 +0530 | [diff] [blame] | 841 | frappe.db.set_value('Bin', bin_name, { |
Nabin Hait | a77b8c9 | 2020-12-21 14:45:50 +0530 | [diff] [blame] | 842 | "valuation_rate": data.valuation_rate, |
| 843 | "actual_qty": data.qty_after_transaction, |
| 844 | "stock_value": data.stock_value |
| 845 | }) |
Nabin Hait | dc82d4f | 2014-04-07 12:02:57 +0530 | [diff] [blame] | 846 | |
marination | 8418c4b | 2021-06-22 21:35:25 +0530 | [diff] [blame] | 847 | |
| 848 | def get_previous_sle_of_current_voucher(args, exclude_current_voucher=False): |
| 849 | """get stock ledger entries filtered by specific posting datetime conditions""" |
| 850 | |
| 851 | args['time_format'] = '%H:%i:%s' |
| 852 | if not args.get("posting_date"): |
| 853 | args["posting_date"] = "1900-01-01" |
| 854 | if not args.get("posting_time"): |
| 855 | args["posting_time"] = "00:00" |
| 856 | |
| 857 | voucher_condition = "" |
| 858 | if exclude_current_voucher: |
| 859 | voucher_no = args.get("voucher_no") |
| 860 | voucher_condition = f"and voucher_no != '{voucher_no}'" |
| 861 | |
| 862 | sle = frappe.db.sql(""" |
| 863 | select *, timestamp(posting_date, posting_time) as "timestamp" |
| 864 | from `tabStock Ledger Entry` |
| 865 | where item_code = %(item_code)s |
| 866 | and warehouse = %(warehouse)s |
| 867 | and is_cancelled = 0 |
| 868 | {voucher_condition} |
| 869 | and timestamp(posting_date, time_format(posting_time, %(time_format)s)) < timestamp(%(posting_date)s, time_format(%(posting_time)s, %(time_format)s)) |
| 870 | order by timestamp(posting_date, posting_time) desc, creation desc |
| 871 | limit 1 |
| 872 | for update""".format(voucher_condition=voucher_condition), args, as_dict=1) |
| 873 | |
| 874 | return sle[0] if sle else frappe._dict() |
| 875 | |
Anand Doshi | 4dc7caa | 2013-01-11 11:44:49 +0530 | [diff] [blame] | 876 | def get_previous_sle(args, for_update=False): |
Anand Doshi | 1b53186 | 2013-01-10 19:29:51 +0530 | [diff] [blame] | 877 | """ |
Nabin Hait | dc82d4f | 2014-04-07 12:02:57 +0530 | [diff] [blame] | 878 | get the last sle on or before the current time-bucket, |
Anand Doshi | 1b53186 | 2013-01-10 19:29:51 +0530 | [diff] [blame] | 879 | to get actual qty before transaction, this function |
| 880 | is called from various transaction like stock entry, reco etc |
Nabin Hait | dc82d4f | 2014-04-07 12:02:57 +0530 | [diff] [blame] | 881 | |
Anand Doshi | 1b53186 | 2013-01-10 19:29:51 +0530 | [diff] [blame] | 882 | args = { |
| 883 | "item_code": "ABC", |
| 884 | "warehouse": "XYZ", |
| 885 | "posting_date": "2012-12-12", |
| 886 | "posting_time": "12:00", |
| 887 | "sle": "name of reference Stock Ledger Entry" |
| 888 | } |
| 889 | """ |
Rushabh Mehta | df9e80c | 2015-02-17 19:55:17 +0530 | [diff] [blame] | 890 | args["name"] = args.get("sle", None) or "" |
| 891 | sle = get_stock_ledger_entries(args, "<=", "desc", "limit 1", for_update=for_update) |
Pratik Vyas | 16371b7 | 2013-09-18 18:31:03 +0530 | [diff] [blame] | 892 | return sle and sle[0] or {} |
Nabin Hait | fb6e434 | 2014-10-15 11:34:40 +0530 | [diff] [blame] | 893 | |
Rohit Waghchaure | 66aa37f | 2019-05-24 16:53:51 +0530 | [diff] [blame] | 894 | def get_stock_ledger_entries(previous_sle, operator=None, |
| 895 | order="desc", limit=None, for_update=False, debug=False, check_serial_no=True): |
Rushabh Mehta | df9e80c | 2015-02-17 19:55:17 +0530 | [diff] [blame] | 896 | """get stock ledger entries filtered by specific posting datetime conditions""" |
Nabin Hait | b9ce104 | 2018-02-01 14:58:50 +0530 | [diff] [blame] | 897 | conditions = " and timestamp(posting_date, posting_time) {0} timestamp(%(posting_date)s, %(posting_time)s)".format(operator) |
| 898 | if previous_sle.get("warehouse"): |
| 899 | conditions += " and warehouse = %(warehouse)s" |
| 900 | elif previous_sle.get("warehouse_condition"): |
| 901 | conditions += " and " + previous_sle.get("warehouse_condition") |
| 902 | |
Rohit Waghchaure | 66aa37f | 2019-05-24 16:53:51 +0530 | [diff] [blame] | 903 | if check_serial_no and previous_sle.get("serial_no"): |
Rohit Waghchaure | bb3e5d0 | 2021-04-24 17:28:33 +0530 | [diff] [blame] | 904 | # conditions += " and serial_no like {}".format(frappe.db.escape('%{0}%'.format(previous_sle.get("serial_no")))) |
| 905 | serial_no = previous_sle.get("serial_no") |
| 906 | conditions += (""" and |
| 907 | ( |
| 908 | serial_no = {0} |
| 909 | or serial_no like {1} |
| 910 | or serial_no like {2} |
| 911 | or serial_no like {3} |
| 912 | ) |
| 913 | """).format(frappe.db.escape(serial_no), frappe.db.escape('{}\n%'.format(serial_no)), |
| 914 | frappe.db.escape('%\n{}'.format(serial_no)), frappe.db.escape('%\n{}\n%'.format(serial_no))) |
Rohit Waghchaure | 05d3bcb | 2019-04-28 18:39:18 +0530 | [diff] [blame] | 915 | |
Rushabh Mehta | df9e80c | 2015-02-17 19:55:17 +0530 | [diff] [blame] | 916 | if not previous_sle.get("posting_date"): |
| 917 | previous_sle["posting_date"] = "1900-01-01" |
| 918 | if not previous_sle.get("posting_time"): |
| 919 | previous_sle["posting_time"] = "00:00" |
| 920 | |
| 921 | if operator in (">", "<=") and previous_sle.get("name"): |
| 922 | conditions += " and name!=%(name)s" |
| 923 | |
Deepesh Garg | 2a9c5ba | 2020-04-30 10:38:58 +0530 | [diff] [blame] | 924 | return frappe.db.sql(""" |
| 925 | select *, timestamp(posting_date, posting_time) as "timestamp" |
| 926 | from `tabStock Ledger Entry` |
Rushabh Mehta | df9e80c | 2015-02-17 19:55:17 +0530 | [diff] [blame] | 927 | where item_code = %%(item_code)s |
Nabin Hait | a77b8c9 | 2020-12-21 14:45:50 +0530 | [diff] [blame] | 928 | and is_cancelled = 0 |
Nabin Hait | b9ce104 | 2018-02-01 14:58:50 +0530 | [diff] [blame] | 929 | %(conditions)s |
Aditya Hase | 0c16424 | 2019-01-07 22:07:13 +0530 | [diff] [blame] | 930 | order by timestamp(posting_date, posting_time) %(order)s, creation %(order)s |
Rushabh Mehta | df9e80c | 2015-02-17 19:55:17 +0530 | [diff] [blame] | 931 | %(limit)s %(for_update)s""" % { |
| 932 | "conditions": conditions, |
| 933 | "limit": limit or "", |
| 934 | "for_update": for_update and "for update" or "", |
| 935 | "order": order |
Rushabh Mehta | 50dc4e9 | 2015-02-19 20:05:45 +0530 | [diff] [blame] | 936 | }, previous_sle, as_dict=1, debug=debug) |
Rushabh Mehta | df9e80c | 2015-02-17 19:55:17 +0530 | [diff] [blame] | 937 | |
Nabin Hait | a77b8c9 | 2020-12-21 14:45:50 +0530 | [diff] [blame] | 938 | def get_sle_by_voucher_detail_no(voucher_detail_no, excluded_sle=None): |
| 939 | return frappe.db.get_value('Stock Ledger Entry', |
| 940 | {'voucher_detail_no': voucher_detail_no, 'name': ['!=', excluded_sle]}, |
| 941 | ['item_code', 'warehouse', 'posting_date', 'posting_time', 'timestamp(posting_date, posting_time) as timestamp'], |
| 942 | as_dict=1) |
Deepesh Garg | 2a9c5ba | 2020-04-30 10:38:58 +0530 | [diff] [blame] | 943 | |
Ankush Menat | ab92652 | 2022-02-19 15:37:03 +0530 | [diff] [blame] | 944 | def get_batch_incoming_rate(item_code, warehouse, batch_no, posting_date, posting_time, creation=None): |
Ankush Menat | ce0514c | 2022-02-15 11:41:41 +0530 | [diff] [blame] | 945 | |
Ankush Menat | 102fff2 | 2022-02-19 15:51:04 +0530 | [diff] [blame] | 946 | Timestamp = CustomFunction('timestamp', ['date', 'time']) |
| 947 | |
| 948 | sle = frappe.qb.DocType("Stock Ledger Entry") |
| 949 | |
| 950 | timestamp_condition = (Timestamp(sle.posting_date, sle.posting_time) < Timestamp(posting_date, posting_time)) |
| 951 | if creation: |
| 952 | timestamp_condition |= ( |
| 953 | (Timestamp(sle.posting_date, sle.posting_time) == Timestamp(posting_date, posting_time)) |
| 954 | & (sle.creation < creation) |
Ankush Menat | ce0514c | 2022-02-15 11:41:41 +0530 | [diff] [blame] | 955 | ) |
Ankush Menat | 102fff2 | 2022-02-19 15:51:04 +0530 | [diff] [blame] | 956 | |
| 957 | batch_details = ( |
| 958 | frappe.qb |
| 959 | .from_(sle) |
| 960 | .select( |
| 961 | Sum(sle.stock_value_difference).as_("batch_value"), |
| 962 | Sum(sle.actual_qty).as_("batch_qty") |
| 963 | ) |
| 964 | .where( |
| 965 | (sle.item_code == item_code) |
| 966 | & (sle.warehouse == warehouse) |
| 967 | & (sle.batch_no == batch_no) |
| 968 | & (sle.is_cancelled == 0) |
| 969 | ) |
| 970 | .where(timestamp_condition) |
| 971 | ).run(as_dict=True) |
Ankush Menat | ce0514c | 2022-02-15 11:41:41 +0530 | [diff] [blame] | 972 | |
| 973 | if batch_details and batch_details[0].batch_qty: |
| 974 | return batch_details[0].batch_value / batch_details[0].batch_qty |
| 975 | |
| 976 | |
Rushabh Mehta | cc8b2b2 | 2017-03-31 12:44:29 +0530 | [diff] [blame] | 977 | def get_valuation_rate(item_code, warehouse, voucher_type, voucher_no, |
Ankush Menat | 342d09a | 2022-02-19 14:28:51 +0530 | [diff] [blame] | 978 | allow_zero_rate=False, currency=None, company=None, raise_error_if_no_rate=True, batch_no=None): |
Rohit Waghchaure | a5f4094 | 2017-06-16 15:21:36 +0530 | [diff] [blame] | 979 | |
Ankush Menat | f7ffe04 | 2021-11-01 13:21:14 +0530 | [diff] [blame] | 980 | if not company: |
| 981 | company = frappe.get_cached_value("Warehouse", warehouse, "company") |
| 982 | |
Ankush Menat | 342d09a | 2022-02-19 14:28:51 +0530 | [diff] [blame] | 983 | last_valuation_rate = None |
| 984 | |
| 985 | # Get moving average rate of a specific batch number |
| 986 | if warehouse and batch_no and frappe.db.get_value("Batch", batch_no, "use_batchwise_valuation"): |
| 987 | last_valuation_rate = frappe.db.sql(""" |
| 988 | select sum(stock_value_difference) / sum(actual_qty) |
| 989 | from `tabStock Ledger Entry` |
| 990 | where |
| 991 | item_code = %s |
| 992 | AND warehouse = %s |
| 993 | AND batch_no = %s |
| 994 | AND is_cancelled = 0 |
| 995 | AND NOT (voucher_no = %s AND voucher_type = %s) |
| 996 | """, |
| 997 | (item_code, warehouse, batch_no, voucher_no, voucher_type)) |
| 998 | |
Ankush Menat | f7ffe04 | 2021-11-01 13:21:14 +0530 | [diff] [blame] | 999 | # Get valuation rate from last sle for the same item and warehouse |
Ankush Menat | 342d09a | 2022-02-19 14:28:51 +0530 | [diff] [blame] | 1000 | if not last_valuation_rate or last_valuation_rate[0][0] is None: |
| 1001 | last_valuation_rate = frappe.db.sql("""select valuation_rate |
| 1002 | from `tabStock Ledger Entry` force index (item_warehouse) |
| 1003 | where |
| 1004 | item_code = %s |
| 1005 | AND warehouse = %s |
| 1006 | AND valuation_rate >= 0 |
| 1007 | AND is_cancelled = 0 |
| 1008 | AND NOT (voucher_no = %s AND voucher_type = %s) |
| 1009 | order by posting_date desc, posting_time desc, name desc limit 1""", (item_code, warehouse, voucher_no, voucher_type)) |
Nabin Hait | fb6e434 | 2014-10-15 11:34:40 +0530 | [diff] [blame] | 1010 | |
| 1011 | if not last_valuation_rate: |
Nabin Hait | a0b967f | 2017-01-18 18:35:58 +0530 | [diff] [blame] | 1012 | # Get valuation rate from last sle for the item against any warehouse |
Nabin Hait | fb6e434 | 2014-10-15 11:34:40 +0530 | [diff] [blame] | 1013 | last_valuation_rate = frappe.db.sql("""select valuation_rate |
Deepesh Garg | 6f107da | 2021-10-12 20:15:55 +0530 | [diff] [blame] | 1014 | from `tabStock Ledger Entry` force index (item_code) |
Mangesh-Khairnar | 0df5134 | 2019-08-19 10:04:52 +0530 | [diff] [blame] | 1015 | where |
| 1016 | item_code = %s |
| 1017 | AND valuation_rate > 0 |
Ankush Menat | 82ea958 | 2022-01-16 20:19:04 +0530 | [diff] [blame] | 1018 | AND is_cancelled = 0 |
Mangesh-Khairnar | 0df5134 | 2019-08-19 10:04:52 +0530 | [diff] [blame] | 1019 | AND NOT(voucher_no = %s AND voucher_type = %s) |
| 1020 | order by posting_date desc, posting_time desc, name desc limit 1""", (item_code, voucher_no, voucher_type)) |
Nabin Hait | fb6e434 | 2014-10-15 11:34:40 +0530 | [diff] [blame] | 1021 | |
Nabin Hait | a645f36 | 2018-03-01 10:31:24 +0530 | [diff] [blame] | 1022 | if last_valuation_rate: |
Nabin Hait | a77b8c9 | 2020-12-21 14:45:50 +0530 | [diff] [blame] | 1023 | return flt(last_valuation_rate[0][0]) |
Nabin Hait | a645f36 | 2018-03-01 10:31:24 +0530 | [diff] [blame] | 1024 | |
| 1025 | # If negative stock allowed, and item delivered without any incoming entry, |
| 1026 | # system does not found any SLE, then take valuation rate from Item |
| 1027 | valuation_rate = frappe.db.get_value("Item", item_code, "valuation_rate") |
Nabin Hait | fb6e434 | 2014-10-15 11:34:40 +0530 | [diff] [blame] | 1028 | |
| 1029 | if not valuation_rate: |
Nabin Hait | a645f36 | 2018-03-01 10:31:24 +0530 | [diff] [blame] | 1030 | # try Item Standard rate |
| 1031 | valuation_rate = frappe.db.get_value("Item", item_code, "standard_rate") |
Nabin Hait | fb6e434 | 2014-10-15 11:34:40 +0530 | [diff] [blame] | 1032 | |
Rushabh Mehta | aedaac6 | 2017-05-04 09:35:19 +0530 | [diff] [blame] | 1033 | if not valuation_rate: |
Nabin Hait | a645f36 | 2018-03-01 10:31:24 +0530 | [diff] [blame] | 1034 | # try in price list |
| 1035 | valuation_rate = frappe.db.get_value('Item Price', |
| 1036 | dict(item_code=item_code, buying=1, currency=currency), |
| 1037 | 'price_list_rate') |
Rushabh Mehta | cc8b2b2 | 2017-03-31 12:44:29 +0530 | [diff] [blame] | 1038 | |
Nabin Hait | 7ba092e | 2018-02-01 10:51:27 +0530 | [diff] [blame] | 1039 | if not allow_zero_rate and not valuation_rate and raise_error_if_no_rate \ |
Rohit Waghchaure | e9ff191 | 2017-06-19 12:54:59 +0530 | [diff] [blame] | 1040 | and cint(erpnext.is_perpetual_inventory_enabled(company)): |
Neil Trini Lasrado | 193c891 | 2017-03-28 17:39:34 +0530 | [diff] [blame] | 1041 | frappe.local.message_log = [] |
Rohit Waghchaure | bb3e5d0 | 2021-04-24 17:28:33 +0530 | [diff] [blame] | 1042 | form_link = get_link_to_form("Item", item_code) |
Marica | 97715f2 | 2020-05-11 20:45:37 +0530 | [diff] [blame] | 1043 | |
| 1044 | message = _("Valuation Rate for the Item {0}, is required to do accounting entries for {1} {2}.").format(form_link, voucher_type, voucher_no) |
Rohit Waghchaure | bb3e5d0 | 2021-04-24 17:28:33 +0530 | [diff] [blame] | 1045 | message += "<br><br>" + _("Here are the options to proceed:") |
Marica | 97715f2 | 2020-05-11 20:45:37 +0530 | [diff] [blame] | 1046 | solutions = "<li>" + _("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) + "</li>" |
Rohit Waghchaure | bb3e5d0 | 2021-04-24 17:28:33 +0530 | [diff] [blame] | 1047 | solutions += "<li>" + _("If not, you can Cancel / Submit this entry") + " {0} ".format(frappe.bold("after")) + _("performing either one below:") + "</li>" |
Marica | 97715f2 | 2020-05-11 20:45:37 +0530 | [diff] [blame] | 1048 | sub_solutions = "<ul><li>" + _("Create an incoming stock transaction for the Item.") + "</li>" |
| 1049 | sub_solutions += "<li>" + _("Mention Valuation Rate in the Item master.") + "</li></ul>" |
| 1050 | msg = message + solutions + sub_solutions + "</li>" |
| 1051 | |
| 1052 | frappe.throw(msg=msg, title=_("Valuation Rate Missing")) |
Nabin Hait | fb6e434 | 2014-10-15 11:34:40 +0530 | [diff] [blame] | 1053 | |
| 1054 | return valuation_rate |
Nabin Hait | a77b8c9 | 2020-12-21 14:45:50 +0530 | [diff] [blame] | 1055 | |
Ankush Menat | e7109c1 | 2021-08-26 16:40:45 +0530 | [diff] [blame] | 1056 | def update_qty_in_future_sle(args, allow_negative_stock=False): |
marination | 8418c4b | 2021-06-22 21:35:25 +0530 | [diff] [blame] | 1057 | """Recalculate Qty after Transaction in future SLEs based on current SLE.""" |
marination | 4038977 | 2021-07-02 17:13:45 +0530 | [diff] [blame] | 1058 | datetime_limit_condition = "" |
marination | 8418c4b | 2021-06-22 21:35:25 +0530 | [diff] [blame] | 1059 | qty_shift = args.actual_qty |
| 1060 | |
| 1061 | # find difference/shift in qty caused by stock reconciliation |
| 1062 | if args.voucher_type == "Stock Reconciliation": |
marination | 4038977 | 2021-07-02 17:13:45 +0530 | [diff] [blame] | 1063 | qty_shift = get_stock_reco_qty_shift(args) |
| 1064 | |
| 1065 | # find the next nearest stock reco so that we only recalculate SLEs till that point |
| 1066 | next_stock_reco_detail = get_next_stock_reco(args) |
| 1067 | if next_stock_reco_detail: |
| 1068 | detail = next_stock_reco_detail[0] |
| 1069 | # add condition to update SLEs before this date & time |
| 1070 | datetime_limit_condition = get_datetime_limit_condition(detail) |
marination | 8418c4b | 2021-06-22 21:35:25 +0530 | [diff] [blame] | 1071 | |
Nabin Hait | 186a045 | 2021-02-18 14:14:21 +0530 | [diff] [blame] | 1072 | frappe.db.sql(""" |
| 1073 | update `tabStock Ledger Entry` |
marination | 8418c4b | 2021-06-22 21:35:25 +0530 | [diff] [blame] | 1074 | set qty_after_transaction = qty_after_transaction + {qty_shift} |
Nabin Hait | 186a045 | 2021-02-18 14:14:21 +0530 | [diff] [blame] | 1075 | where |
| 1076 | item_code = %(item_code)s |
| 1077 | and warehouse = %(warehouse)s |
| 1078 | and voucher_no != %(voucher_no)s |
| 1079 | and is_cancelled = 0 |
| 1080 | and (timestamp(posting_date, posting_time) > timestamp(%(posting_date)s, %(posting_time)s) |
| 1081 | or ( |
| 1082 | timestamp(posting_date, posting_time) = timestamp(%(posting_date)s, %(posting_time)s) |
| 1083 | and creation > %(creation)s |
| 1084 | ) |
| 1085 | ) |
marination | 4038977 | 2021-07-02 17:13:45 +0530 | [diff] [blame] | 1086 | {datetime_limit_condition} |
| 1087 | """.format(qty_shift=qty_shift, datetime_limit_condition=datetime_limit_condition), args) |
Nabin Hait | 186a045 | 2021-02-18 14:14:21 +0530 | [diff] [blame] | 1088 | |
| 1089 | validate_negative_qty_in_future_sle(args, allow_negative_stock) |
| 1090 | |
marination | 4038977 | 2021-07-02 17:13:45 +0530 | [diff] [blame] | 1091 | def get_stock_reco_qty_shift(args): |
| 1092 | stock_reco_qty_shift = 0 |
| 1093 | if args.get("is_cancelled"): |
| 1094 | if args.get("previous_qty_after_transaction"): |
| 1095 | # get qty (balance) that was set at submission |
| 1096 | last_balance = args.get("previous_qty_after_transaction") |
| 1097 | stock_reco_qty_shift = flt(args.qty_after_transaction) - flt(last_balance) |
| 1098 | else: |
| 1099 | stock_reco_qty_shift = flt(args.actual_qty) |
| 1100 | else: |
| 1101 | # reco is being submitted |
| 1102 | last_balance = get_previous_sle_of_current_voucher(args, |
| 1103 | exclude_current_voucher=True).get("qty_after_transaction") |
| 1104 | |
| 1105 | if last_balance is not None: |
| 1106 | stock_reco_qty_shift = flt(args.qty_after_transaction) - flt(last_balance) |
| 1107 | else: |
| 1108 | stock_reco_qty_shift = args.qty_after_transaction |
| 1109 | |
| 1110 | return stock_reco_qty_shift |
| 1111 | |
| 1112 | def get_next_stock_reco(args): |
| 1113 | """Returns next nearest stock reconciliaton's details.""" |
| 1114 | |
| 1115 | return frappe.db.sql(""" |
| 1116 | select |
| 1117 | name, posting_date, posting_time, creation, voucher_no |
| 1118 | from |
marination | 8c44126 | 2021-07-02 17:46:05 +0530 | [diff] [blame] | 1119 | `tabStock Ledger Entry` |
marination | 4038977 | 2021-07-02 17:13:45 +0530 | [diff] [blame] | 1120 | where |
| 1121 | item_code = %(item_code)s |
| 1122 | and warehouse = %(warehouse)s |
| 1123 | and voucher_type = 'Stock Reconciliation' |
| 1124 | and voucher_no != %(voucher_no)s |
| 1125 | and is_cancelled = 0 |
| 1126 | and (timestamp(posting_date, posting_time) > timestamp(%(posting_date)s, %(posting_time)s) |
| 1127 | or ( |
| 1128 | timestamp(posting_date, posting_time) = timestamp(%(posting_date)s, %(posting_time)s) |
| 1129 | and creation > %(creation)s |
| 1130 | ) |
| 1131 | ) |
| 1132 | limit 1 |
| 1133 | """, args, as_dict=1) |
| 1134 | |
| 1135 | def get_datetime_limit_condition(detail): |
marination | 4038977 | 2021-07-02 17:13:45 +0530 | [diff] [blame] | 1136 | return f""" |
| 1137 | and |
| 1138 | (timestamp(posting_date, posting_time) < timestamp('{detail.posting_date}', '{detail.posting_time}') |
| 1139 | or ( |
| 1140 | timestamp(posting_date, posting_time) = timestamp('{detail.posting_date}', '{detail.posting_time}') |
| 1141 | and creation < '{detail.creation}' |
| 1142 | ) |
| 1143 | )""" |
| 1144 | |
Ankush Menat | e7109c1 | 2021-08-26 16:40:45 +0530 | [diff] [blame] | 1145 | def validate_negative_qty_in_future_sle(args, allow_negative_stock=False): |
Ankush Menat | eb8b424 | 2022-02-12 13:08:28 +0530 | [diff] [blame] | 1146 | if allow_negative_stock or is_negative_stock_allowed(item_code=args.item_code): |
Ankush Menat | 5eba575 | 2021-12-07 23:03:52 +0530 | [diff] [blame] | 1147 | return |
| 1148 | if not (args.actual_qty < 0 or args.voucher_type == "Stock Reconciliation"): |
| 1149 | return |
Deepesh Garg | b4be292 | 2021-01-28 13:09:56 +0530 | [diff] [blame] | 1150 | |
Ankush Menat | 5eba575 | 2021-12-07 23:03:52 +0530 | [diff] [blame] | 1151 | neg_sle = get_future_sle_with_negative_qty(args) |
| 1152 | if neg_sle: |
| 1153 | message = _("{0} units of {1} needed in {2} on {3} {4} for {5} to complete this transaction.").format( |
| 1154 | abs(neg_sle[0]["qty_after_transaction"]), |
| 1155 | frappe.get_desk_link('Item', args.item_code), |
| 1156 | frappe.get_desk_link('Warehouse', args.warehouse), |
| 1157 | neg_sle[0]["posting_date"], neg_sle[0]["posting_time"], |
| 1158 | frappe.get_desk_link(neg_sle[0]["voucher_type"], neg_sle[0]["voucher_no"])) |
| 1159 | |
| 1160 | frappe.throw(message, NegativeStockError, title='Insufficient Stock') |
| 1161 | |
| 1162 | |
| 1163 | if not args.batch_no: |
| 1164 | return |
| 1165 | |
| 1166 | neg_batch_sle = get_future_sle_with_negative_batch_qty(args) |
| 1167 | if neg_batch_sle: |
| 1168 | message = _("{0} units of {1} needed in {2} on {3} {4} for {5} to complete this transaction.").format( |
| 1169 | abs(neg_batch_sle[0]["cumulative_total"]), |
| 1170 | frappe.get_desk_link('Batch', args.batch_no), |
| 1171 | frappe.get_desk_link('Warehouse', args.warehouse), |
| 1172 | neg_batch_sle[0]["posting_date"], neg_batch_sle[0]["posting_time"], |
| 1173 | frappe.get_desk_link(neg_batch_sle[0]["voucher_type"], neg_batch_sle[0]["voucher_no"])) |
| 1174 | frappe.throw(message, NegativeStockError, title="Insufficient Stock for Batch") |
| 1175 | |
Nabin Hait | a77b8c9 | 2020-12-21 14:45:50 +0530 | [diff] [blame] | 1176 | |
| 1177 | def get_future_sle_with_negative_qty(args): |
| 1178 | return frappe.db.sql(""" |
| 1179 | select |
| 1180 | qty_after_transaction, posting_date, posting_time, |
| 1181 | voucher_type, voucher_no |
| 1182 | from `tabStock Ledger Entry` |
Deepesh Garg | b4be292 | 2021-01-28 13:09:56 +0530 | [diff] [blame] | 1183 | where |
Nabin Hait | a77b8c9 | 2020-12-21 14:45:50 +0530 | [diff] [blame] | 1184 | item_code = %(item_code)s |
| 1185 | and warehouse = %(warehouse)s |
| 1186 | and voucher_no != %(voucher_no)s |
| 1187 | and timestamp(posting_date, posting_time) >= timestamp(%(posting_date)s, %(posting_time)s) |
| 1188 | and is_cancelled = 0 |
Nabin Hait | 186a045 | 2021-02-18 14:14:21 +0530 | [diff] [blame] | 1189 | and qty_after_transaction < 0 |
Nabin Hait | 243d59b | 2021-02-02 16:55:13 +0530 | [diff] [blame] | 1190 | order by timestamp(posting_date, posting_time) asc |
Nabin Hait | a77b8c9 | 2020-12-21 14:45:50 +0530 | [diff] [blame] | 1191 | limit 1 |
Sagar Vora | e50324a | 2021-03-31 12:44:03 +0530 | [diff] [blame] | 1192 | """, args, as_dict=1) |
Ankush Menat | 6a014d1 | 2021-04-12 20:21:27 +0530 | [diff] [blame] | 1193 | |
Ankush Menat | 5eba575 | 2021-12-07 23:03:52 +0530 | [diff] [blame] | 1194 | |
| 1195 | def get_future_sle_with_negative_batch_qty(args): |
| 1196 | return frappe.db.sql(""" |
| 1197 | with batch_ledger as ( |
| 1198 | select |
| 1199 | posting_date, posting_time, voucher_type, voucher_no, |
| 1200 | sum(actual_qty) over (order by posting_date, posting_time, creation) as cumulative_total |
| 1201 | from `tabStock Ledger Entry` |
| 1202 | where |
| 1203 | item_code = %(item_code)s |
| 1204 | and warehouse = %(warehouse)s |
| 1205 | and batch_no=%(batch_no)s |
| 1206 | and is_cancelled = 0 |
| 1207 | order by posting_date, posting_time, creation |
| 1208 | ) |
| 1209 | select * from batch_ledger |
| 1210 | where |
| 1211 | cumulative_total < 0.0 |
| 1212 | and timestamp(posting_date, posting_time) >= timestamp(%(posting_date)s, %(posting_time)s) |
| 1213 | limit 1 |
| 1214 | """, args, as_dict=1) |
Ankush Menat | eb8b424 | 2022-02-12 13:08:28 +0530 | [diff] [blame] | 1215 | |
| 1216 | |
| 1217 | def is_negative_stock_allowed(*, item_code: Optional[str] = None) -> bool: |
| 1218 | if cint(frappe.db.get_single_value("Stock Settings", "allow_negative_stock", cache=True)): |
| 1219 | return True |
| 1220 | if item_code and cint(frappe.db.get_value("Item", item_code, "allow_negative_stock", cache=True)): |
| 1221 | return True |
| 1222 | return False |