<commit_before># Please edit this list and import only required elements
import webnotes

from webnotes.utils import add_days, add_months, add_years, cint, cstr, date_diff, default_fields, flt, fmt_money, formatdate, generate_hash, getTraceback, get_defaults, get_first_day, get_last_day, getdate, has_common, month_name, now, nowdate, replace_newlines, sendmail, set_default, str_esc_quote, user_format, validate_email_add
from webnotes.model import db_exists
from webnotes.model.doc import Document, addchild, removechild, getchildren, make_autoname, SuperDocType
from webnotes.model.doclist import getlist, copy_doclist
from webnotes.model.code import get_obj, get_server_obj, run_server_obj, updatedb, check_syntax
from webnotes import session, form, is_testing, msgprint, errprint

set = webnotes.conn.set
sql = webnotes.conn.sql
get_value = webnotes.conn.get_value
in_transaction = webnotes.conn.in_transaction
convert_to_lists = webnotes.conn.convert_to_lists

# -----------------------------------------------------------------------------------------

from utilities.transaction_base import TransactionBase

class DocType(TransactionBase):
  def __init__(self, doc, doclist=[]):
    self.doc = doc
    self.doclist = doclist
    self.defaults = get_defaults()
    self.tname = 'Purchase Receipt Detail'
    self.fname = 'purchase_receipt_details'
    self.count = 0

  # Autoname
  # ---------
  def autoname(self):
    self.doc.name = make_autoname(self.doc.naming_series+'.#####')


  # Client Trigger Functions
  #----------------------------------------------------------------------------------------------------

  def get_default_schedule_date(self):
    get_obj(dt = 'Purchase Common').get_default_schedule_date(self)

#-----------------Validation For Fiscal Year------------------------
  def validate_fiscal_year(self):
    get_obj(dt = 'Purchase Common').validate_fiscal_year(self.doc.fiscal_year,self.doc.transaction_date,'Transaction Date')


  # Get Item Details
  def get_item_details(self, arg = ''):
    return get_obj(dt='Purchase Common').get_item_details(self,arg)

  # Get UOM Details
  def get_uom_details(self, arg = ''):
    return get_obj(dt='Purchase Common').get_uom_details(arg)

  # GET TERMS & CONDITIONS
  # =====================================================================================
  def get_tc_details(self):
    return get_obj('Purchase Common').get_tc_details(self)

  # get available qty at warehouse
  def get_bin_details(self, arg = ''):
    return get_obj(dt='Purchase Common').get_bin_details(arg)

  # Pull Purchase Order
  def get_po_details(self):
    self.validate_prev_docname()
    get_obj('DocType Mapper', 'Purchase Order-Purchase Receipt').dt_map('Purchase Order', 'Purchase Receipt', self.doc.purchase_order_no, self.doc, self.doclist, "[['Purchase Order','Purchase Receipt'],['PO Detail', 'Purchase Receipt Detail'],['Purchase Tax Detail','Purchase Tax Detail']]")

  # validate if PO has been pulled twice
  def validate_prev_docname(self):
    for d in getlist(self.doclist, 'purchase_receipt_details'):
      if self.doc.purchase_order_no and d.prevdoc_docname and self.doc.purchase_order_no == d.prevdoc_docname:
        msgprint(cstr(self.doc.purchase_order_no) + " Purchase Order details have already been pulled. ")
        raise Exception


  # validation
  #-------------------------------------------------------------------------------------------------------------
  # validate accepted and rejected qty
  def validate_accepted_rejected_qty(self):
    for d in getlist(self.doclist, "purchase_receipt_details"):

      # If Reject Qty than Rejected warehouse is mandatory
      if flt(d.rejected_qty) and (not self.doc.rejected_warehouse):
        msgprint("Rejected Warehouse is necessary if there are rejections. See 'Receipt Items'")
        raise Exception

      # Check Received Qty = Accepted Qty + Rejected Qty
      if ((flt(d.qty) + flt(d.rejected_qty)) != flt(d.received_qty)):

        msgprint("Sum of Accepted Qty and Rejected Qty must be equal to Received quantity. Error for Item: " + cstr(d.item_code))
        raise Exception


  # update valuation rate
  def update_valuation_rate(self):
    total_b_cost = flt(self.doc.buying_cost_transport) + flt(self.doc.buying_cost_taxes) + flt(self.doc.buying_cost_other)
    for d in getlist(self.doclist, 'purchase_receipt_details'):
      if flt(self.doc.net_total) and flt(d.qty):
        #d.valuation_rate = (flt(d.purchase_rate) + ((flt(d.amount) * (total_b_cost)) / (self.doc.net_total * flt(d.qty))) + (flt(d.rm_supp_cost) / flt(d.qty))) / flt(d.conversion_factor)
        d.valuation_rate = (flt(d.purchase_rate) + ((flt(d.amount) * (total_b_cost)) / (self.doc.net_total * flt(d.qty))) + (flt(d.rm_supp_cost) / flt(d.qty)) + (flt(d.item_tax_amount)/flt(d.qty))) / flt(d.conversion_factor)

  # Check for Stopped status
  def check_for_stopped_status(self, pc_obj):
    check_list =[]
    for d in getlist(self.doclist, 'purchase_receipt_details'):
      if d.fields.has_key('prevdoc_docname') and d.prevdoc_docname and d.prevdoc_docname not in check_list:
        check_list.append(d.prevdoc_docname)
        pc_obj.check_for_stopped_status( d.prevdoc_doctype, d.prevdoc_docname)

  #check in manage account if purchase order required or not.
  # ====================================================================================
  def po_required(self):
    res = sql("select value from `tabSingles` where doctype = 'Manage Account' and field = 'po_required'")
    if res and res[0][0]== 'Yes':
       for d in getlist(self.doclist,'purchase_receipt_details'):
         if not d.prevdoc_docname:
           msgprint("Purchse Order No. required against item %s"%d.item_code)
           raise Exception


  # validate
  def validate(self):
    self.po_required()
    self.validate_fiscal_year()
    set(self.doc, 'status', 'Draft')       # set status as "Draft"
    self.validate_accepted_rejected_qty()
    self.validate_inspection()             # Validate Inspection
    get_obj('Stock Ledger').validate_serial_no(self, 'purchase_receipt_details')

    pc_obj = get_obj(dt='Purchase Common')
    pc_obj.validate_for_items(self)
    pc_obj.validate_mandatory(self)
    pc_obj.validate_conversion_rate(self)
    pc_obj.get_prevdoc_date(self)
    pc_obj.validate_reference_value(self)
    self.check_for_stopped_status(pc_obj)

    # get total in words
    dcc = TransactionBase().get_company_currency(self.doc.company)
    self.doc.in_words = pc_obj.get_total_in_words(dcc, self.doc.grand_total)
    self.doc.in_words_import = pc_obj.get_total_in_words(self.doc.currency, self.doc.grand_total_import)
    # update valuation rate
    self.update_valuation_rate()


  # On Update
  # ----------------------------------------------------------------------------------------------------
  def on_update(self):<commit_msg>Validate if another GRN exists having same supplier and challan no. - then throw exception<commit_after># Please edit this list and import only required elements
import webnotes

from webnotes.utils import add_days, add_months, add_years, cint, cstr, date_diff, default_fields, flt, fmt_money, formatdate, generate_hash, getTraceback, get_defaults, get_first_day, get_last_day, getdate, has_common, month_name, now, nowdate, replace_newlines, sendmail, set_default, str_esc_quote, user_format, validate_email_add
from webnotes.model import db_exists
from webnotes.model.doc import Document, addchild, removechild, getchildren, make_autoname, SuperDocType
from webnotes.model.doclist import getlist, copy_doclist
from webnotes.model.code import get_obj, get_server_obj, run_server_obj, updatedb, check_syntax
from webnotes import session, form, is_testing, msgprint, errprint

set = webnotes.conn.set
sql = webnotes.conn.sql
get_value = webnotes.conn.get_value
in_transaction = webnotes.conn.in_transaction
convert_to_lists = webnotes.conn.convert_to_lists

# -----------------------------------------------------------------------------------------

from utilities.transaction_base import TransactionBase

class DocType(TransactionBase):
  def __init__(self, doc, doclist=[]):
    self.doc = doc
    self.doclist = doclist
    self.defaults = get_defaults()
    self.tname = 'Purchase Receipt Detail'
    self.fname = 'purchase_receipt_details'
    self.count = 0

  # Autoname
  # ---------
  def autoname(self):
    self.doc.name = make_autoname(self.doc.naming_series+'.#####')


  # Client Trigger Functions
  #----------------------------------------------------------------------------------------------------

  def get_default_schedule_date(self):
    get_obj(dt = 'Purchase Common').get_default_schedule_date(self)

#-----------------Validation For Fiscal Year------------------------
  def validate_fiscal_year(self):
    get_obj(dt = 'Purchase Common').validate_fiscal_year(self.doc.fiscal_year,self.doc.transaction_date,'Transaction Date')


  # Get Item Details
  def get_item_details(self, arg = ''):
    return get_obj(dt='Purchase Common').get_item_details(self,arg)

  # Get UOM Details
  def get_uom_details(self, arg = ''):
    return get_obj(dt='Purchase Common').get_uom_details(arg)

  # GET TERMS & CONDITIONS
  # =====================================================================================
  def get_tc_details(self):
    return get_obj('Purchase Common').get_tc_details(self)

  # get available qty at warehouse
  def get_bin_details(self, arg = ''):
    return get_obj(dt='Purchase Common').get_bin_details(arg)

  # Pull Purchase Order
  def get_po_details(self):
    self.validate_prev_docname()
    get_obj('DocType Mapper', 'Purchase Order-Purchase Receipt').dt_map('Purchase Order', 'Purchase Receipt', self.doc.purchase_order_no, self.doc, self.doclist, "[['Purchase Order','Purchase Receipt'],['PO Detail', 'Purchase Receipt Detail'],['Purchase Tax Detail','Purchase Tax Detail']]")

  # validate if PO has been pulled twice
  def validate_prev_docname(self):
    for d in getlist(self.doclist, 'purchase_receipt_details'):
      if self.doc.purchase_order_no and d.prevdoc_docname and self.doc.purchase_order_no == d.prevdoc_docname:
        msgprint(cstr(self.doc.purchase_order_no) + " Purchase Order details have already been pulled. ")
        raise Exception


  # validation
  #-------------------------------------------------------------------------------------------------------------
  # validate accepted and rejected qty
  def validate_accepted_rejected_qty(self):
    for d in getlist(self.doclist, "purchase_receipt_details"):

      # If Reject Qty than Rejected warehouse is mandatory
      if flt(d.rejected_qty) and (not self.doc.rejected_warehouse):
        msgprint("Rejected Warehouse is necessary if there are rejections. See 'Receipt Items'")
        raise Exception

      # Check Received Qty = Accepted Qty + Rejected Qty
      if ((flt(d.qty) + flt(d.rejected_qty)) != flt(d.received_qty)):

        msgprint("Sum of Accepted Qty and Rejected Qty must be equal to Received quantity. Error for Item: " + cstr(d.item_code))
        raise Exception


  def validate_challan_no(self):
    "Validate if same challan no exists for same supplier in a purchase receipt"
    if self.doc.challan_no:
      exists = webnotes.conn.sql("""
	    SELECT name FROM `tabPurchase Receipt`
	    WHERE name!=%s AND supplier=%s AND challan_no=%s""", (self.doc.name, self.doc.supplier, self.doc.challan_no))
      if exists:
	    webnotes.msgprint("Another Purchase Receipt using the same Challan No. already exists.\
		  Please enter a valid Challan No.", raise_exception=1)


  # update valuation rate
  def update_valuation_rate(self):
    total_b_cost = flt(self.doc.buying_cost_transport) + flt(self.doc.buying_cost_taxes) + flt(self.doc.buying_cost_other)
    for d in getlist(self.doclist, 'purchase_receipt_details'):
      if flt(self.doc.net_total) and flt(d.qty):
        #d.valuation_rate = (flt(d.purchase_rate) + ((flt(d.amount) * (total_b_cost)) / (self.doc.net_total * flt(d.qty))) + (flt(d.rm_supp_cost) / flt(d.qty))) / flt(d.conversion_factor)
        d.valuation_rate = (flt(d.purchase_rate) + ((flt(d.amount) * (total_b_cost)) / (self.doc.net_total * flt(d.qty))) + (flt(d.rm_supp_cost) / flt(d.qty)) + (flt(d.item_tax_amount)/flt(d.qty))) / flt(d.conversion_factor)

  # Check for Stopped status
  def check_for_stopped_status(self, pc_obj):
    check_list =[]
    for d in getlist(self.doclist, 'purchase_receipt_details'):
      if d.fields.has_key('prevdoc_docname') and d.prevdoc_docname and d.prevdoc_docname not in check_list:
        check_list.append(d.prevdoc_docname)
        pc_obj.check_for_stopped_status( d.prevdoc_doctype, d.prevdoc_docname)

  #check in manage account if purchase order required or not.
  # ====================================================================================
  def po_required(self):
    res = sql("select value from `tabSingles` where doctype = 'Manage Account' and field = 'po_required'")
    if res and res[0][0]== 'Yes':
       for d in getlist(self.doclist,'purchase_receipt_details'):
         if not d.prevdoc_docname:
           msgprint("Purchse Order No. required against item %s"%d.item_code)
           raise Exception


  # validate
  def validate(self):
    self.po_required()
    self.validate_fiscal_year()
    set(self.doc, 'status', 'Draft')       # set status as "Draft"
    self.validate_accepted_rejected_qty()
    self.validate_inspection()             # Validate Inspection
    get_obj('Stock Ledger').validate_serial_no(self, 'purchase_receipt_details')
    self.validate_challan_no()

    pc_obj = get_obj(dt='Purchase Common')
    pc_obj.validate_for_items(self)
    pc_obj.validate_mandatory(self)
    pc_obj.validate_conversion_rate(self)
    pc_obj.get_prevdoc_date(self)
    pc_obj.validate_reference_value(self)
    self.check_for_stopped_status(pc_obj)

    # get total in words
    dcc = TransactionBase().get_company_currency(self.doc.company)
    self.doc.in_words = pc_obj.get_total_in_words(dcc, self.doc.grand_total)
    self.doc.in_words_import = pc_obj.get_total_in_words(self.doc.currency, self.doc.grand_total_import)
    # update valuation rate
    self.update_valuation_rate()


  # On Update
  # ----------------------------------------------------------------------------------------------------
  def on_update(self):
{'fraction_non_alphanumeric': 0.18283166109253066, 'fraction_numerical': 0.00048773690078037906, 'mean_word_length': 3.3310199155099576, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '7657567', 'n_tokens_mistral': 4622, 'n_tokens_neox': 4464, 'n_words': 971}