def calculate_unclaimed_taxable_benefits(self, payroll_period): # get total sum of benefits paid total_benefits_paid = flt( dataent.db.sql( """ select sum(sd.amount) from `tabSalary Detail` sd join `tabSalary Slip` ss on sd.parent=ss.name where sd.parentfield='earnings' and sd.is_tax_applicable=1 and is_flexible_benefit=1 and ss.docstatus=1 and ss.employee=%(employee)s and ss.start_date between %(start_date)s and %(end_date)s and ss.end_date between %(start_date)s and %(end_date)s """, { "employee": self.employee, "start_date": payroll_period.start_date, "end_date": self.start_date })[0][0]) # get total benefits claimed total_benefits_claimed = flt( dataent.db.sql( """ select sum(claimed_amount) from `tabEmployee Benefit Claim` where docstatus=1 and employee=%s and claim_date between %s and %s """, (self.employee, payroll_period.start_date, self.end_date))[0][0]) return total_benefits_paid - total_benefits_claimed
def get_total_exemption_amount(declarations): exemptions = dataent._dict() for d in declarations: exemptions.setdefault(d.exemption_category, dataent._dict()) category_max_amount = exemptions.get(d.exemption_category).max_amount if not category_max_amount: category_max_amount = dataent.db.get_value( "Employee Tax Exemption Category", d.exemption_category, "max_amount") exemptions.get( d.exemption_category).max_amount = category_max_amount sub_category_exemption_amount = d.max_amount \ if (d.max_amount and flt(d.amount) > flt(d.max_amount)) else d.amount exemptions.get(d.exemption_category).setdefault( "total_exemption_amount", 0.0) exemptions.get(d.exemption_category).total_exemption_amount += flt( sub_category_exemption_amount) if category_max_amount and exemptions.get( d.exemption_category ).total_exemption_amount > category_max_amount: exemptions.get(d.exemption_category ).total_exemption_amount = category_max_amount total_exemption_amount = sum( [flt(d.total_exemption_amount) for d in exemptions.values()]) return total_exemption_amount
def update_packing_list_item(doc, packing_item_code, qty, main_item_row, description): item = get_packing_item_details(packing_item_code, doc.company) # check if exists exists = 0 for d in doc.get("packed_items"): if d.parent_item == main_item_row.item_code and d.item_code == packing_item_code and\ d.parent_detail_docname == main_item_row.name and d.description == description: pi, exists = d, 1 break if not exists: pi = doc.append('packed_items', {}) pi.parent_item = main_item_row.item_code pi.item_code = packing_item_code pi.item_name = item.item_name pi.parent_detail_docname = main_item_row.name pi.description = item.description pi.uom = item.stock_uom pi.qty = flt(qty) pi.description = description if not pi.warehouse: pi.warehouse = (main_item_row.warehouse if ((doc.get('is_pos') or not item.default_warehouse) and main_item_row.warehouse) else item.default_warehouse) if not pi.batch_no: pi.batch_no = cstr(main_item_row.get("batch_no")) if not pi.target_warehouse: pi.target_warehouse = main_item_row.get("target_warehouse") bin = get_bin_qty(packing_item_code, pi.warehouse) pi.actual_qty = flt(bin.get("actual_qty")) pi.projected_qty = flt(bin.get("projected_qty"))
def _set_in_company_currency(self, doc, fields): """set values in base currency""" for f in fields: val = flt( flt(doc.get(f), doc.precision(f)) * self.doc.conversion_rate, doc.precision("base_" + f)) doc.set("base_" + f, val)
def get_invoice_tax_map(invoice_list, invoice_expense_map, expense_accounts): tax_details = dataent.db.sql(""" select parent, account_head, case add_deduct_tax when "Add" then sum(base_tax_amount_after_discount_amount) else sum(base_tax_amount_after_discount_amount) * -1 end as tax_amount from `tabPurchase Taxes and Charges` where parent in (%s) and category in ('Total', 'Valuation and Total') and base_tax_amount_after_discount_amount != 0 group by parent, account_head, add_deduct_tax """ % ', '.join(['%s'] * len(invoice_list)), tuple([inv.name for inv in invoice_list]), as_dict=1) invoice_tax_map = {} for d in tax_details: if d.account_head in expense_accounts: if d.account_head in invoice_expense_map[d.parent]: invoice_expense_map[d.parent][d.account_head] += flt( d.tax_amount) else: invoice_expense_map[d.parent][d.account_head] = flt( d.tax_amount) else: invoice_tax_map.setdefault(d.parent, dataent._dict()).setdefault( d.account_head, []) invoice_tax_map[d.parent][d.account_head] = flt(d.tax_amount) return invoice_expense_map, invoice_tax_map
def get_average_rate_based_on_group_by(self): # sum buying / selling totals for group for key in list(self.grouped): if self.filters.get("group_by") != "Invoice": for i, row in enumerate(self.grouped[key]): if i==0: new_row = row else: new_row.qty += row.qty new_row.buying_amount += flt(row.buying_amount, self.currency_precision) new_row.base_amount += flt(row.base_amount, self.currency_precision) new_row = self.set_average_rate(new_row) self.grouped_data.append(new_row) else: for i, row in enumerate(self.grouped[key]): if row.parent in self.returned_invoices \ and row.item_code in self.returned_invoices[row.parent]: returned_item_rows = self.returned_invoices[row.parent][row.item_code] for returned_item_row in returned_item_rows: row.qty += returned_item_row.qty row.base_amount += flt(returned_item_row.base_amount, self.currency_precision) row.buying_amount = flt(row.qty * row.buying_rate, self.currency_precision) if row.qty or row.base_amount: row = self.set_average_rate(row) self.grouped_data.append(row)
def calculate_margin(self, item): rate_with_margin = 0.0 base_rate_with_margin = 0.0 if item.price_list_rate: if item.pricing_rule and not self.doc.ignore_pricing_rule: pricing_rule = dataent.get_doc('Pricing Rule', item.pricing_rule) if (pricing_rule.margin_type == 'Amount' and pricing_rule.currency == self.doc.currency)\ or (pricing_rule.margin_type == 'Percentage'): item.margin_type = pricing_rule.margin_type item.margin_rate_or_amount = pricing_rule.margin_rate_or_amount else: item.margin_type = None item.margin_rate_or_amount = 0.0 if item.margin_type and item.margin_rate_or_amount: margin_value = item.margin_rate_or_amount if item.margin_type == 'Amount' else flt( item.price_list_rate) * flt( item.margin_rate_or_amount) / 100 rate_with_margin = flt( item.price_list_rate) + flt(margin_value) base_rate_with_margin = flt(rate_with_margin) * flt( self.doc.conversion_rate) return rate_with_margin, base_rate_with_margin
def update_stock_ledger_entries(self, sle): sle.valuation_rate = get_valuation_rate(sle.item_code, sle.warehouse, self.doctype, self.name, currency=self.company_currency, company=self.company) sle.stock_value = flt(sle.qty_after_transaction) * flt( sle.valuation_rate) sle.stock_value_difference = flt(sle.actual_qty) * flt( sle.valuation_rate) if sle.name: dataent.db.sql( """ update `tabStock Ledger Entry` set stock_value = %(stock_value)s, valuation_rate = %(valuation_rate)s, stock_value_difference = %(stock_value_difference)s where name = %(name)s""", (sle)) return sle
def make_write_off_gl_entry(self, gl_entries): # writeoff account includes petty difference in the invoice amount # and the amount that is paid if self.write_off_account and flt(self.write_off_amount): write_off_account_currency = get_account_currency(self.write_off_account) gl_entries.append( self.get_gl_dict({ "account": self.credit_to, "party_type": "Supplier", "party": self.supplier, "against": self.write_off_account, "debit": self.base_write_off_amount, "debit_in_account_currency": self.base_write_off_amount \ if self.party_account_currency==self.company_currency else self.write_off_amount, "against_voucher": self.return_against if cint(self.is_return) and self.return_against else self.name, "against_voucher_type": self.doctype, "cost_center": self.cost_center }, self.party_account_currency) ) gl_entries.append( self.get_gl_dict({ "account": self.write_off_account, "against": self.supplier, "credit": flt(self.base_write_off_amount), "credit_in_account_currency": self.base_write_off_amount \ if write_off_account_currency==self.company_currency else self.write_off_amount, "cost_center": self.cost_center or self.write_off_cost_center }) )
def get_last_purchase_rate(self): """get last purchase rates for all items""" conversion_rate = flt(self.get('conversion_rate')) or 1.0 for d in self.get("items"): if d.item_code: last_purchase_details = get_last_purchase_details( d.item_code, self.name) if last_purchase_details: d.base_price_list_rate = ( last_purchase_details['base_price_list_rate'] * (flt(d.conversion_factor) or 1.0)) d.discount_percentage = last_purchase_details[ 'discount_percentage'] d.base_rate = last_purchase_details['base_rate'] * (flt( d.conversion_factor) or 1.0) d.price_list_rate = d.base_price_list_rate / conversion_rate d.rate = d.base_rate / conversion_rate d.last_purchase_rate = d.rate else: item_last_purchase_rate = dataent.get_cached_value( "Item", d.item_code, "last_purchase_rate") if item_last_purchase_rate: d.base_price_list_rate = d.base_rate = d.price_list_rate \ = d.rate = d.last_purchase_rate = item_last_purchase_rate
def update_item(obj, target, source_parent): target.conversion_factor = obj.conversion_factor target.qty = flt(flt(obj.stock_qty) - flt(obj.ordered_qty)) / target.conversion_factor target.stock_qty = (target.qty * target.conversion_factor) if getdate(target.schedule_date) < getdate(nowdate()): target.schedule_date = None
def test_payment_entry_against_si_usd_to_usd(self): si = create_sales_invoice(customer="_Test Customer USD", debit_to="_Test Receivable USD - _TC", currency="USD", conversion_rate=50) pe = get_payment_entry("Sales Invoice", si.name, bank_account="_Test Bank USD - _TC") pe.reference_no = "1" pe.reference_date = "2016-01-01" pe.target_exchange_rate = 50 pe.insert() pe.submit() expected_gle = dict((d[0], d) for d in [ ["_Test Receivable USD - _TC", 0, 5000, si.name], ["_Test Bank USD - _TC", 5000.0, 0, None] ]) self.validate_gl_entries(pe.name, expected_gle) outstanding_amount = flt(dataent.db.get_value("Sales Invoice", si.name, "outstanding_amount")) self.assertEqual(outstanding_amount, 0) pe.cancel() self.assertFalse(self.get_gle(pe.name)) outstanding_amount = flt(dataent.db.get_value("Sales Invoice", si.name, "outstanding_amount")) self.assertEqual(outstanding_amount, 100)
def get_status(self): '''Returns status based on whether it is draft, submitted, scrapped or depreciated''' if self.docstatus == 0: status = "Draft" elif self.docstatus == 1: status = "Submitted" if self.journal_entry_for_scrap: status = "Scrapped" elif self.finance_books: idx = self.get_default_finance_book_idx() or 0 expected_value_after_useful_life = self.finance_books[ idx].expected_value_after_useful_life value_after_depreciation = self.finance_books[ idx].value_after_depreciation if flt(value_after_depreciation ) <= expected_value_after_useful_life: status = "Fully Depreciated" elif flt(value_after_depreciation) < flt( self.gross_purchase_amount): status = 'Partially Depreciated' elif self.docstatus == 2: status = "Cancelled" return status
def get_salesperson_item_month_map(filters): import datetime salesperson_details = get_salesperson_details(filters) tdd = get_target_distribution_details(filters) item_groups = get_item_groups() sales_persons = get_sales_persons() sales_person_achievement_dict = {} for sd in salesperson_details: achieved_details = get_achieved_details(filters, sd.name, sales_persons, sd.item_group, item_groups) for month_id in range(1, 13): month = datetime.date(2013, month_id, 1).strftime('%B') sales_person_achievement_dict.setdefault(sd.name, {}).setdefault(sd.item_group, {})\ .setdefault(month, dataent._dict({ "target": 0.0, "achieved": 0.0 })) sales_target_achieved = sales_person_achievement_dict[sd.name][sd.item_group][month] month_percentage = tdd.get(sd.distribution_id, {}).get(month, 0) \ if sd.distribution_id else 100.0/12 if (filters["target_on"] == "Quantity"): sales_target_achieved.target = flt(sd.target_qty) * month_percentage / 100 else: sales_target_achieved.target = flt(sd.target_amount) * month_percentage / 100 sales_target_achieved.achieved = achieved_details.get(month, dataent._dict())\ .get(filters["target_on"].lower()) return sales_person_achievement_dict
def validate_conversion_rate(args, meta): from epaas.controllers.accounts_controller import validate_conversion_rate if (not args.conversion_rate and args.currency==dataent.get_cached_value('Company', args.company, "default_currency")): args.conversion_rate = 1.0 # validate currency conversion rate validate_conversion_rate(args.currency, args.conversion_rate, meta.get_label("conversion_rate"), args.company) args.conversion_rate = flt(args.conversion_rate, get_field_precision(meta.get_field("conversion_rate"), dataent._dict({"fields": args}))) if args.price_list: if (not args.plc_conversion_rate and args.price_list_currency==dataent.db.get_value("Price List", args.price_list, "currency", cache=True)): args.plc_conversion_rate = 1.0 # validate price list currency conversion rate if not args.get("price_list_currency"): throw(_("Price List Currency not selected")) else: validate_conversion_rate(args.price_list_currency, args.plc_conversion_rate, meta.get_label("plc_conversion_rate"), args.company) if meta.get_field("plc_conversion_rate"): args.plc_conversion_rate = flt(args.plc_conversion_rate, get_field_precision(meta.get_field("plc_conversion_rate"), dataent._dict({"fields": args})))
def execute(filters=None): columns = get_columns(filters) consumed_details = get_consumed_details(filters) supplier_details = get_suppliers_details(filters) material_transfer_vouchers = get_material_transfer_vouchers() data = [] for item_code, suppliers in iteritems(supplier_details): consumed_qty = consumed_amount = delivered_qty = delivered_amount = 0.0 total_qty = total_amount = 0.0 if consumed_details.get(item_code): for cd in consumed_details.get(item_code): if (cd.voucher_no not in material_transfer_vouchers): if cd.voucher_type == "Delivery Note": delivered_qty += abs(flt(cd.actual_qty)) delivered_amount += abs(flt(cd.stock_value_difference)) elif cd.voucher_type != "Delivery Note": consumed_qty += abs(flt(cd.actual_qty)) consumed_amount += abs(flt(cd.stock_value_difference)) if consumed_qty or consumed_amount or delivered_qty or delivered_amount: total_qty += delivered_qty + consumed_qty total_amount += delivered_amount + consumed_amount row = [cd.item_code, cd.item_name, cd.description, cd.stock_uom, \ consumed_qty, consumed_amount, delivered_qty, delivered_amount, \ total_qty, total_amount, ','.join(list(set(suppliers)))] data.append(row) return columns, data
def insert_entries(self, row): """Insert Stock Ledger Entries""" args = dataent._dict({ "doctype": "Stock Ledger Entry", "item_code": row.item_code, "warehouse": row.warehouse, "posting_date": self.posting_date, "posting_time": self.posting_time, "voucher_type": self.doctype, "voucher_no": self.name, "company": self.company, "stock_uom": dataent.db.get_value("Item", row.item_code, "stock_uom"), "is_cancelled": "No", "qty_after_transaction": flt(row.qty, row.precision("qty")), "valuation_rate": flt(row.valuation_rate, row.precision("valuation_rate")) }) self.make_sl_entries([args])
def get_chart_data(data, period_list): fuel_exp_data, service_exp_data, fueldata, servicedata = [], [], [], [] service_exp_data = [] fueldata = [] for period in period_list: total_fuel_exp = 0 total_ser_exp = 0 for row in data: if row["Date"] <= period.to_date and row[ "Date"] >= period.from_date: total_fuel_exp += flt(row["Fuel Price"]) total_ser_exp += flt(row["Service Expense"]) fueldata.append([period.key, total_fuel_exp]) servicedata.append([period.key, total_ser_exp]) labels = [period.key for period in period_list] fuel_exp_data = [row[1] for row in fueldata] service_exp_data = [row[1] for row in servicedata] datasets = [] if fuel_exp_data: datasets.append({'name': 'Fuel Expenses', 'values': fuel_exp_data}) if service_exp_data: datasets.append({ 'name': 'Service Expenses', 'values': service_exp_data }) chart = {"data": {'labels': labels, 'datasets': datasets}} chart["type"] = "line" return chart
def determine_exclusive_rate(self): if not any((cint(tax.included_in_print_rate) for tax in self.doc.get("taxes"))): return for item in self.doc.get("items"): item_tax_map = self._load_item_tax_rate(item.item_tax_rate) cumulated_tax_fraction = 0 for i, tax in enumerate(self.doc.get("taxes")): tax.tax_fraction_for_current_item = self.get_current_tax_fraction( tax, item_tax_map) if i == 0: tax.grand_total_fraction_for_current_item = 1 + tax.tax_fraction_for_current_item else: tax.grand_total_fraction_for_current_item = \ self.doc.get("taxes")[i-1].grand_total_fraction_for_current_item \ + tax.tax_fraction_for_current_item cumulated_tax_fraction += tax.tax_fraction_for_current_item if cumulated_tax_fraction and not self.discount_amount_applied and item.qty: item.net_amount = flt(item.amount / (1 + cumulated_tax_fraction)) item.net_rate = flt(item.net_amount / item.qty, item.precision("net_rate")) item.discount_percentage = flt( item.discount_percentage, item.precision("discount_percentage")) self._set_in_company_currency(item, ["net_rate", "net_amount"])
def get_fifo_queue(filters): item_details = {} for d in get_stock_ledger_entries(filters): item_details.setdefault(d.name, {"details": d, "fifo_queue": []}) fifo_queue = item_details[d.name]["fifo_queue"] if d.voucher_type == "Stock Reconciliation": d.actual_qty = flt(d.qty_after_transaction) - flt( item_details[d.name].get("qty_after_transaction", 0)) if d.actual_qty > 0: fifo_queue.append([d.actual_qty, d.posting_date]) else: qty_to_pop = abs(d.actual_qty) while qty_to_pop: batch = fifo_queue[0] if fifo_queue else [0, None] if 0 < batch[0] <= qty_to_pop: # if batch qty > 0 # not enough or exactly same qty in current batch, clear batch qty_to_pop -= batch[0] fifo_queue.pop(0) else: # all from current batch batch[0] -= qty_to_pop qty_to_pop = 0 item_details[d.name]["qty_after_transaction"] = d.qty_after_transaction return item_details
def get_itemised_tax(taxes, with_tax_account=False): itemised_tax = {} for tax in taxes: if getattr(tax, "category", None) and tax.category == "Valuation": continue item_tax_map = json.loads( tax.item_wise_tax_detail) if tax.item_wise_tax_detail else {} if item_tax_map: for item_code, tax_data in item_tax_map.items(): itemised_tax.setdefault(item_code, dataent._dict()) tax_rate = 0.0 tax_amount = 0.0 if isinstance(tax_data, list): tax_rate = flt(tax_data[0]) tax_amount = flt(tax_data[1]) else: tax_rate = flt(tax_data) itemised_tax[item_code][tax.description] = dataent._dict( dict(tax_rate=tax_rate, tax_amount=tax_amount)) if with_tax_account: itemised_tax[item_code][ tax.description].tax_account = tax.account_head return itemised_tax
def test_exchange_rate_strict(self): # strict currency settings dataent.db.set_value("Accounts Settings", None, "allow_stale", 0) dataent.db.set_value("Accounts Settings", None, "stale_days", 1) exchange_rate = get_exchange_rate("USD", "INR", "2016-01-01") self.assertEqual(exchange_rate, 60.0) # Will fetch from fixer.io self.clear_cache() exchange_rate = get_exchange_rate("USD", "INR", "2016-01-15") self.assertEqual(flt(exchange_rate, 3), 67.79) exchange_rate = get_exchange_rate("USD", "INR", "2016-01-30") self.assertEqual(exchange_rate, 62.9) # Exchange rate as on 15th Dec, 2015, should be fetched from fixer.io self.clear_cache() exchange_rate = get_exchange_rate("USD", "INR", "2015-12-15") self.assertEqual(flt(exchange_rate, 3), 66.894) exchange_rate = get_exchange_rate("INR", "NGN", "2016-01-10") self.assertEqual(exchange_rate, 65.1) # NGN is not available on fixer.io so these should return 0 exchange_rate = get_exchange_rate("INR", "NGN", "2016-01-09") self.assertEqual(exchange_rate, 0) exchange_rate = get_exchange_rate("INR", "NGN", "2016-01-11") self.assertEqual(exchange_rate, 0)
def execute(filters=None): if not filters: filters = {} float_preceision = dataent.db.get_default("float_preceision") condition = get_condition(filters) avg_daily_outgoing = 0 diff = ((getdate(filters.get("to_date")) - getdate(filters.get("from_date"))).days) + 1 if diff <= 0: dataent.throw(_("'From Date' must be after 'To Date'")) columns = get_columns() items = get_item_info(filters) consumed_item_map = get_consumed_items(condition) delivered_item_map = get_delivered_items(condition) data = [] for item in items: total_outgoing = consumed_item_map.get( item.name, 0) + delivered_item_map.get(item.name, 0) avg_daily_outgoing = flt(total_outgoing / diff, float_preceision) reorder_level = (avg_daily_outgoing * flt(item.lead_time_days)) + flt( item.safety_stock) data.append([ item.name, item.item_name, item.item_group, item.brand, item.description, item.safety_stock, item.lead_time_days, consumed_item_map.get(item.name, 0), delivered_item_map.get(item.name, 0), total_outgoing, avg_daily_outgoing, reorder_level ]) return columns, data
def set_total_gain_loss(self): total_gain_loss = 0 for d in self.accounts: d.gain_loss = flt(d.new_balance_in_base_currency, d.precision("new_balance_in_base_currency")) \ - flt(d.balance_in_base_currency, d.precision("balance_in_base_currency")) total_gain_loss += flt(d.gain_loss, d.precision("gain_loss")) self.total_gain_loss = flt(total_gain_loss, self.precision("total_gain_loss"))
def get_shipping_amount_from_rules(self, value): for condition in self.get("conditions"): if not condition.to_value or (flt(condition.from_value) <= value <= flt(condition.to_value)): return condition.shipping_amount return 0.0
def get_accounts_data(self, account=None): accounts = [] self.validate_mandatory() company_currency = epaas.get_company_currency(self.company) precision = get_field_precision(dataent.get_meta("Exchange Rate Revaluation Account") .get_field("new_balance_in_base_currency"), company_currency) account_details = self.get_accounts_from_gle() for d in account_details: current_exchange_rate = d.balance / d.balance_in_account_currency \ if d.balance_in_account_currency else 0 new_exchange_rate = get_exchange_rate(d.account_currency, company_currency, self.posting_date) new_balance_in_base_currency = flt(d.balance_in_account_currency * new_exchange_rate) gain_loss = flt(new_balance_in_base_currency, precision) - flt(d.balance, precision) if gain_loss: accounts.append({ "account": d.account, "party_type": d.party_type, "party": d.party, "account_currency": d.account_currency, "balance_in_base_currency": d.balance, "balance_in_account_currency": d.balance_in_account_currency, "current_exchange_rate": current_exchange_rate, "new_exchange_rate": new_exchange_rate, "new_balance_in_base_currency": new_balance_in_base_currency }) if not accounts: self.throw_invalid_response_message(account_details) return accounts
def execute(filters=None): if not filters: filters = {} columns = get_columns(filters) conditions = get_condition(filters) item_map = get_item_details(conditions) pl = get_price_list() last_purchase_rate = get_last_purchase_rate() bom_rate = get_item_bom_rate() val_rate_map = get_valuation_rate() from epaas.accounts.utils import get_currency_precision precision = get_currency_precision() or 2 data = [] for item in sorted(item_map): data.append([ item, item_map[item]["item_name"], item_map[item]["item_group"], item_map[item]["brand"], item_map[item]["description"], item_map[item]["stock_uom"], flt(last_purchase_rate.get(item, 0), precision), flt(val_rate_map.get(item, 0), precision), pl.get(item, {}).get("Selling"), pl.get(item, {}).get("Buying"), flt(bom_rate.get(item, 0), precision) ]) return columns, data
def get_price_list_rate(args, item_doc, out): meta = dataent.get_meta(args.parenttype or args.doctype) if meta.get_field("currency") or args.get('currency'): pl_details = get_price_list_currency_and_exchange_rate(args) args.update(pl_details) validate_price_list(args) if meta.get_field("currency"): validate_conversion_rate(args, meta) price_list_rate = get_price_list_rate_for(args, item_doc.name) or 0 # variant if not price_list_rate and item_doc.variant_of: price_list_rate = get_price_list_rate_for(args, item_doc.variant_of) # insert in database if not price_list_rate: if args.price_list and args.rate: insert_item_price(args) return {} out.price_list_rate = flt(price_list_rate) * flt(args.plc_conversion_rate) \ / flt(args.conversion_rate) if not out.price_list_rate and args.transaction_type=="buying": from epaas.stock.doctype.item.item import get_last_purchase_details out.update(get_last_purchase_details(item_doc.name, args.name, args.conversion_rate))
def update_last_purchase_rate(doc, is_submit): """updates last_purchase_rate in item table for each item""" import dataent.utils this_purchase_date = dataent.utils.getdate(doc.get('posting_date') or doc.get('transaction_date')) for d in doc.get("items"): # get last purchase details last_purchase_details = get_last_purchase_details(d.item_code, doc.name) # compare last purchase date and this transaction's date last_purchase_rate = None if last_purchase_details and \ (last_purchase_details.purchase_date > this_purchase_date): last_purchase_rate = last_purchase_details['base_rate'] elif is_submit == 1: # even if this transaction is the latest one, it should be submitted # for it to be considered for latest purchase rate if flt(d.conversion_factor): last_purchase_rate = flt(d.base_rate) / flt(d.conversion_factor) else: dataent.throw(_("UOM Conversion factor is required in row {0}").format(d.idx)) # update last purchsae rate if last_purchase_rate: dataent.db.sql("""update `tabItem` set last_purchase_rate = %s where name = %s""", (flt(last_purchase_rate), d.item_code))
def get_territory_item_month_map(filters): import datetime territory_details = get_territory_details(filters) tdd = get_target_distribution_details(filters) item_groups = get_item_groups() territory_item_group_dict = {} for td in territory_details: achieved_details = get_achieved_details(filters, td.name, item_groups) for month_id in range(1, 13): month = datetime.date(2013, month_id, 1).strftime('%B') territory_item_group_dict.setdefault(td.name, {}).setdefault(td.item_group, {})\ .setdefault(month, dataent._dict({ "target": 0.0, "achieved": 0.0 })) target_achieved = territory_item_group_dict[td.name][ td.item_group][month] month_percentage = tdd.get(td.distribution_id, {}).get(month, 0) \ if td.distribution_id else 100.0/12 if (filters["target_on"] == "Quantity"): target_achieved.target = flt( td.target_qty) * month_percentage / 100 else: target_achieved.target = flt( td.target_amount) * month_percentage / 100 target_achieved.achieved = achieved_details.get(td.item_group, {}).get(month, {})\ .get(filters["target_on"].lower()) return territory_item_group_dict