def get_bootinfo(): """build and return boot info""" bootinfo = webnotes._dict() hooks = webnotes.get_hooks() doclist = [] # profile get_profile(bootinfo) # control panel cp = webnotes.model.doc.getsingle('Control Panel') # system info bootinfo['control_panel'] = webnotes._dict(cp.copy()) bootinfo['sysdefaults'] = webnotes.defaults.get_defaults() bootinfo['server_date'] = webnotes.utils.nowdate() bootinfo["send_print_in_body_and_attachment"] = webnotes.conn.get_value("Email Settings", None, "send_print_in_body_and_attachment") if webnotes.session['user'] != 'Guest': bootinfo['user_info'] = get_fullnames() bootinfo['sid'] = webnotes.session['sid']; # home page bootinfo.modules = {} for app in webnotes.get_installed_apps(): try: bootinfo.modules.update(webnotes.get_attr(app + ".config.desktop.data") or {}) except ImportError, e: pass
def get_last_purchase_details(item_code, doc_name=None, conversion_rate=1.0): """returns last purchase details in stock uom""" # get last purchase order item details last_purchase_order = webnotes.conn.sql("""\ select po.name, po.transaction_date, po.conversion_rate, po_item.conversion_factor, po_item.purchase_ref_rate, po_item.discount_rate, po_item.purchase_rate from `tabPurchase Order` po, `tabPurchase Order Item` po_item where po.docstatus = 1 and po_item.item_code = %s and po.name != %s and po.name = po_item.parent order by po.transaction_date desc, po.name desc limit 1""", (item_code, cstr(doc_name)), as_dict=1) # get last purchase receipt item details last_purchase_receipt = webnotes.conn.sql("""\ select pr.name, pr.posting_date, pr.posting_time, pr.conversion_rate, pr_item.conversion_factor, pr_item.purchase_ref_rate, pr_item.discount_rate, pr_item.purchase_rate from `tabPurchase Receipt` pr, `tabPurchase Receipt Item` pr_item where pr.docstatus = 1 and pr_item.item_code = %s and pr.name != %s and pr.name = pr_item.parent order by pr.posting_date desc, pr.posting_time desc, pr.name desc limit 1""", (item_code, cstr(doc_name)), as_dict=1) purchase_order_date = getdate(last_purchase_order and last_purchase_order[0].transaction_date \ or "1900-01-01") purchase_receipt_date = getdate(last_purchase_receipt and \ last_purchase_receipt[0].posting_date or "1900-01-01") if (purchase_order_date > purchase_receipt_date) or \ (last_purchase_order and not last_purchase_receipt): # use purchase order last_purchase = last_purchase_order[0] purchase_date = purchase_order_date elif (purchase_receipt_date > purchase_order_date) or \ (last_purchase_receipt and not last_purchase_order): # use purchase receipt last_purchase = last_purchase_receipt[0] purchase_date = purchase_receipt_date else: return webnotes._dict() conversion_factor = flt(last_purchase.conversion_factor) out = webnotes._dict({ "purchase_ref_rate": flt(last_purchase.purchase_ref_rate) / conversion_factor, "purchase_rate": flt(last_purchase.purchase_rate) / conversion_factor, "discount_rate": flt(last_purchase.discount_rate), "purchase_date": purchase_date }) conversion_rate = flt(conversion_rate) or 1.0 out.update({ "import_ref_rate": out.purchase_ref_rate / conversion_rate, "import_rate": out.purchase_rate / conversion_rate, "rate": out.purchase_rate }) return out
def build_field_columns(dt): doctype_dl = webnotes.model.doctype.get(dt) tablecolumns = filter(None, [doctype_dl.get_field(f[0]) for f in webnotes.conn.sql('desc `tab%s`' % dt)]) tablecolumns.sort(lambda a, b: a.idx - b.idx) if dt==doctype: column_start_end[dt] = webnotes._dict({"start": 0}) else: column_start_end[dt] = webnotes._dict({"start": len(columns)}) append_field_column(webnotes._dict({ "fieldname": "name", "label": "ID", "fieldtype": "Data", "reqd": 1, "idx": 0, "info": "Leave blank for new records" }), True) for docfield in tablecolumns: append_field_column(docfield, True) # all non mandatory fields for docfield in tablecolumns: append_field_column(docfield, False) # append DocType name tablerow[column_start_end[dt].start + 1] = dt if dt!=doctype: tablerow[column_start_end[dt].start + 2] = doctype_parentfield[dt] column_start_end[dt].end = len(columns) + 1
def get_values_from_single(self, fields, filters, doctype, as_dict=False, debug=False): if fields=="*" or isinstance(filters, dict): r = self.sql("""select field, value from tabSingles where doctype=%s""", doctype) # check if single doc matches with filters values = webnotes._dict(r) if isinstance(filters, dict): for key, value in filters.items(): if values.get(key) != value: return [] if as_dict: return values and [values] or [] if isinstance(fields, list): return [map(lambda d: values.get(d), fields)] else: r = self.sql("""select field, value from tabSingles where field in (%s) and doctype=%s""" \ % (', '.join(['%s'] * len(fields)), '%s'), tuple(fields) + (doctype,), as_dict=False, debug=debug) if as_dict: return r and [webnotes._dict(r)] or [] else: return r and [[i[1] for i in r]] or []
def validate_currency(args, item, meta=None): from webnotes.model.meta import get_field_precision if not meta: meta = webnotes.get_doctype(args.doctype) # validate conversion rate if meta.get_field("currency"): validate_conversion_rate(args.currency, args.conversion_rate, meta.get_label("conversion_rate"), args.company) # round it args.conversion_rate = flt(args.conversion_rate, get_field_precision(meta.get_field("conversion_rate"), webnotes._dict({"fields": args}))) # validate price list conversion rate if meta.get_field("price_list_currency") and (args.selling_price_list or args.buying_price_list) \ and args.price_list_currency: validate_conversion_rate(args.price_list_currency, args.plc_conversion_rate, meta.get_label("plc_conversion_rate"), args.company) # round it args.plc_conversion_rate = flt(args.plc_conversion_rate, get_field_precision(meta.get_field("plc_conversion_rate"), webnotes._dict({"fields": args})))
def uncommonify_doclist(dl): """ Expands an commonified doclist """ # first one has common values common_values = dl[0] common_dict = webnotes._dict() final = [] idx_dict = {} for d in dl[1:]: if 'name' in d and d['name']=='__common__': # common for a doctype - del d['name'] common_dict[d['doctype']] = d else: dt = d['doctype'] if not dt in idx_dict: idx_dict[dt] = 1; d1 = webnotes._dict(common_values.copy()) # update from common and global d1.update(common_dict[dt]) d1.update(d) # idx by sequence d1['idx'] = idx_dict[dt] # increment idx idx_dict[dt] += 1 final.append(d1) return final
def update_event(args, field_map): args = webnotes._dict(json.loads(args)) field_map = webnotes._dict(json.loads(field_map)) w = webnotes.bean(args.doctype, args.name) w.doc.fields[field_map.start] = args[field_map.start] w.doc.fields[field_map.end] = args[field_map.end] w.save()
def execute(filters=None): if not filters: filters = {} employee_filters = filters.get("company") and [["Employee", "company", "=", filters.get("company")]] or None employees = runreport(doctype="Employee", fields=["name", "employee_name", "department"], filters=employee_filters) leave_types = webnotes.conn.sql_list("select name from `tabLeave Type`") if filters.get("fiscal_year"): fiscal_years = [filters["fiscal_year"]] else: fiscal_years = webnotes.conn.sql_list("select name from `tabFiscal Year` order by name desc") employee_in = '", "'.join([e.name for e in employees]) allocations = webnotes.conn.sql( """select employee, fiscal_year, leave_type, total_leaves_allocated from `tabLeave Allocation` where docstatus=1 and employee in ("%s")""" % employee_in, as_dict=True, ) applications = webnotes.conn.sql( """select employee, fiscal_year, leave_type, SUM(total_leave_days) as leaves from `tabLeave Application` where status="Approved" and docstatus = 1 and employee in ("%s") group by employee, fiscal_year, leave_type""" % employee_in, as_dict=True, ) columns = ["Fiscal Year", "Employee:Link/Employee:150", "Employee Name::200", "Department::150"] for leave_type in leave_types: columns.append(leave_type + " Allocated:Float") columns.append(leave_type + " Taken:Float") columns.append(leave_type + " Balance:Float") data = {} for d in allocations: data.setdefault( (d.fiscal_year, d.employee, d.leave_type), webnotes._dict() ).allocation = d.total_leaves_allocated for d in applications: data.setdefault((d.fiscal_year, d.employee, d.leave_type), webnotes._dict()).leaves = d.leaves result = [] for fiscal_year in fiscal_years: for employee in employees: row = [fiscal_year, employee.name, employee.employee_name, employee.department] result.append(row) for leave_type in leave_types: tmp = data.get((fiscal_year, employee.name, leave_type), webnotes._dict()) row.append(tmp.allocation or 0) row.append(tmp.leaves or 0) row.append((tmp.allocation or 0) - (tmp.leaves or 0)) return columns, result
def build_page(page_name): if not webnotes.conn: webnotes.connect() sitemap = get_website_sitemap() page_options = sitemap.get(page_name) if not page_options: if page_name=="index": # page not found, try home page home_page = get_home_page() page_options = sitemap.get(home_page) if not page_options: raise PageNotFoundError page_options["page_name"] = home_page else: raise PageNotFoundError else: page_options["page_name"] = page_name basepath = webnotes.utils.get_base_path() module = None no_cache = False if page_options.get("controller"): module = webnotes.get_module(page_options["controller"]) no_cache = getattr(module, "no_cache", False) # if generator, then load bean, pass arguments if page_options.get("is_generator"): if not module: raise Exception("Generator controller not defined") name = webnotes.conn.get_value(module.doctype, { page_options.get("page_name_field", "page_name"): page_options["page_name"]}) obj = webnotes.get_obj(module.doctype, name, with_children=True) if hasattr(obj, 'get_context'): obj.get_context() context = webnotes._dict(obj.doc.fields) context["obj"] = obj else: # page context = webnotes._dict({ 'name': page_name }) if module and hasattr(module, "get_context"): context.update(module.get_context()) context.update(get_website_settings()) jenv = webnotes.get_jenv() context["base_template"] = jenv.get_template(webnotes.get_config().get("base_template")) template_name = page_options['template'] html = jenv.get_template(template_name).render(context) if not no_cache: webnotes.cache().set_value("page:" + page_name, html) return html
def get_data(rows, company_abbr): start_row = 0 data = [] start_row_idx = 0 for i in xrange(len(rows)): r = rows[i] if r[0]: if start_row and i >= start_row: if not start_row_idx: start_row_idx = i d, acc_dict = webnotes._dict(), webnotes._dict() for cidx in xrange(len(columns)): d[columns[cidx]] = r[cidx] if accounts: total_debit = total_credit = 0 for acc_idx in xrange(len(accounts)): col_idx = len(columns) + acc_idx if flt(r[col_idx]) != 0: if not acc_dict.get(accounts[acc_idx]): acc_dict[accounts[acc_idx]] = 0 acc_dict[accounts[acc_idx]] += flt(r[col_idx]) if flt(r[col_idx]) > 0: total_debit += flt(r[col_idx]) else: total_credit += abs(flt(r[col_idx])) d['total_debit'] = total_debit d['total_credit'] = total_credit data.append([d, acc_dict]) if r[0]=="--------Data----------": start_row = i+2 # check for empty columns empty_columns = [j+1 for j, c in enumerate(rows[i+1]) if not c] if empty_columns: raise Exception, """Column No(s). %s %s empty. \ Please remove them and try again.""" % (comma_and(empty_columns), len(empty_columns)==1 and "is" or "are") columns = [c.replace(" ", "_").lower() for c in rows[i+1] if not c.endswith(" - " + company_abbr)] accounts = [c for c in rows[i+1] if c.endswith(" - " + company_abbr)] if not accounts: webnotes.msgprint(_("""No Account found in csv file, May be company abbreviation is not correct"""), raise_exception=1) if accounts and (len(columns) != rows[i+1].index(accounts[0])): webnotes.msgprint(_("""All account columns should be after \ standard columns and on the right. If you entered it properly, next probable reason \ could be wrong account name. Please rectify it in the file and try again."""), raise_exception=1) return data, start_row_idx
def get_item_list(self, obj, is_stopped=0): """get item list""" il = [] for d in getlist(obj.doclist, obj.fname): reserved_warehouse = "" reserved_qty_for_main_item = 0 if obj.doc.doctype == "Sales Order": if (webnotes.conn.get_value("Item", d.item_code, "is_stock_item") == 'Yes' or self.has_sales_bom(d.item_code)) and not d.reserved_warehouse: webnotes.throw(_("Please enter Reserved Warehouse for item ") + d.item_code + _(" as it is stock Item or packing item")) reserved_warehouse = d.reserved_warehouse if flt(d.qty) > flt(d.delivered_qty): reserved_qty_for_main_item = flt(d.qty) - flt(d.delivered_qty) if obj.doc.doctype == "Delivery Note" and d.against_sales_order: # if SO qty is 10 and there is tolerance of 20%, then it will allow DN of 12. # But in this case reserved qty should only be reduced by 10 and not 12 already_delivered_qty = self.get_already_delivered_qty(obj.doc.name, d.against_sales_order, d.prevdoc_detail_docname) so_qty, reserved_warehouse = self.get_so_qty_and_warehouse(d.prevdoc_detail_docname) if already_delivered_qty + d.qty > so_qty: reserved_qty_for_main_item = -(so_qty - already_delivered_qty) else: reserved_qty_for_main_item = -flt(d.qty) if self.has_sales_bom(d.item_code): for p in getlist(obj.doclist, 'packing_details'): if p.parent_detail_docname == d.name and p.parent_item == d.item_code: # the packing details table's qty is already multiplied with parent's qty il.append(webnotes._dict({ 'warehouse': p.warehouse, 'reserved_warehouse': reserved_warehouse, 'item_code': p.item_code, 'qty': flt(p.qty), 'reserved_qty': (flt(p.qty)/flt(d.qty)) * reserved_qty_for_main_item, 'uom': p.uom, 'batch_no': cstr(p.batch_no).strip(), 'serial_no': cstr(p.serial_no).strip(), 'name': d.name })) else: il.append(webnotes._dict({ 'warehouse': d.warehouse, 'reserved_warehouse': reserved_warehouse, 'item_code': d.item_code, 'qty': d.qty, 'reserved_qty': reserved_qty_for_main_item, 'uom': d.stock_uom, 'batch_no': cstr(d.batch_no).strip(), 'serial_no': cstr(d.serial_no).strip(), 'name': d.name })) return il
def get_transaction_context(doctype, name): customer = webnotes.conn.get_value("Contact", {"email_id": webnotes.session.user}, "customer") bean = webnotes.bean(doctype, name) if bean.doc.customer != customer: return { "bean": webnotes._dict({ "doc": webnotes._dict({"name": _("Not Allowed")}) }) } else: return { "bean": bean }
def fmap(self): if not hasattr(self, "_fmap"): if self.doc.doctype in ["Lead", "Quotation", "Sales Order", "Sales Invoice", "Delivery Note"]: self._fmap = webnotes._dict( { "exchange_rate": "conversion_rate", "taxes_and_charges": "other_charges", "taxes_and_charges_master": "charge", "taxes_and_charges_total": "other_charges_total", "net_total_print": "net_total_print", "grand_total_print": "grand_total_export", "grand_total_in_words": "grand_total_in_words", "grand_total_in_words_print": "grand_total_in_words_print", "rounded_total_print": "rounded_total_export", "rounded_total_in_words": "in_words", "rounded_total_in_words_print": "in_words_export", "print_ref_rate": "ref_rate", "discount": "adj_rate", "print_rate": "export_rate", "print_amount": "export_amount", "ref_rate": "base_ref_rate", "rate": "basic_rate", "plc_exchange_rate": "plc_conversion_rate", "tax_calculation": "other_charges_calculation", "cost_center": "cost_center_other_charges", }) else: self._fmap = webnotes._dict({ "exchange_rate": "conversion_rate", "taxes_and_charges": "purchase_tax_details", "taxes_and_charges_master": "purchase_other_charges", "taxes_and_charges_total": "total_tax", "net_total_print": "net_total_import", "grand_total_print": "grand_total_import", "grand_total_in_words": "in_words", "grand_total_in_words_print": "in_words_import", "rounded_total_print": "rounded_total_print", "rounded_total_in_words": "rounded_total_in_words", "rounded_total_in_words_print": "rounded_total_in_words_print", "print_ref_rate": "import_ref_rate", "discount": "discount_rate", "print_rate": "import_rate", "print_amount": "import_amount", "ref_rate": "purchase_ref_rate", "rate": "purchase_rate", "valuation_tax_amount": "item_tax_amount" }) if self.doc.doctype == "Purchase Invoice": self._fmap.update({ "rate": "rate" }) return self._fmap or webnotes._dict()
def get_item_sales_bom(): item_sales_bom = {} for d in webnotes.conn.sql("""select parenttype, parent, parent_item, item_code, warehouse, -1*qty as total_qty from `tabDelivery Note Packing Item` where docstatus=1""", as_dict=True): item_sales_bom.setdefault(d.parenttype, webnotes._dict()).setdefault(d.parent, webnotes._dict()).setdefault(d.parent_item, []).append(d) return item_sales_bom
def initialize_gle_map(gl_entries): gle_map = webnotes._dict() for gle in gl_entries: gle_map.setdefault(gle.account, webnotes._dict({ "opening": 0, "entries": [], "total_debit": 0, "total_credit": 0, "closing": 0 })) return gle_map
def __init__(self, user=None): self.user = user self.sid = webnotes.form_dict.get('sid') or webnotes.request.cookies.get('sid', 'Guest') self.data = webnotes._dict({'user':user,'data': webnotes._dict({})}) self.time_diff = None if webnotes.form_dict.get('cmd')=='login': self.start() return self.load()
def get_bootinfo(): """build and return boot info""" bootinfo = webnotes._dict() doclist = [] # profile get_profile(bootinfo) # control panel cp = webnotes.model.doc.getsingle('Control Panel') # system info bootinfo['control_panel'] = webnotes._dict(cp.copy()) bootinfo['sysdefaults'] = webnotes.defaults.get_defaults() bootinfo['server_date'] = webnotes.utils.nowdate() bootinfo["send_print_in_body_and_attachment"] = webnotes.conn.get_value("Email Settings", None, "send_print_in_body_and_attachment") if webnotes.session['user'] != 'Guest': bootinfo['user_info'] = get_fullnames() bootinfo['sid'] = webnotes.session['sid']; # home page bootinfo.modules = webnotes.get_config().modules bootinfo.hidden_modules = webnotes.conn.get_global("hidden_modules") bootinfo.doctype_icons = dict(webnotes.conn.sql("""select name, icon from tabDocType where ifnull(icon,'')!=''""")) bootinfo.doctype_icons.update(dict(webnotes.conn.sql("""select name, icon from tabPage where ifnull(icon,'')!=''"""))) add_home_page(bootinfo, doclist) add_allowed_pages(bootinfo) load_translations(bootinfo) load_conf_settings(bootinfo) # ipinfo if webnotes.session['data'].get('ipinfo'): bootinfo['ipinfo'] = webnotes.session['data']['ipinfo'] # add docs bootinfo['docs'] = doclist # plugins try: import startup.boot startup.boot.boot_session(bootinfo) except ImportError: pass from webnotes.model.utils import compress bootinfo['docs'] = compress(bootinfo['docs']) return bootinfo
def __init__(self, user=None): self.user = user self.sid = webnotes.form_dict.get("sid") or webnotes.incoming_cookies.get("sid", "Guest") self.data = webnotes._dict({"user": user, "data": webnotes._dict({})}) self.time_diff = None if webnotes.form_dict.get("cmd") == "login": self.start() return self.load()
def get_bootinfo(): """build and return boot info""" bootinfo = webnotes._dict() doclist = [] # profile get_profile(bootinfo) # control panel cp = webnotes.model.doc.getsingle("Control Panel") # system info bootinfo["control_panel"] = webnotes._dict(cp.copy()) bootinfo["sysdefaults"] = webnotes.defaults.get_defaults() bootinfo["server_date"] = webnotes.utils.nowdate() bootinfo["send_print_in_body_and_attachment"] = webnotes.conn.get_value( "Email Settings", None, "send_print_in_body_and_attachment" ) if webnotes.session["user"] != "Guest": bootinfo["user_info"] = get_fullnames() bootinfo["sid"] = webnotes.session["sid"] # home page bootinfo.modules = webnotes.get_config().modules bootinfo.hidden_modules = webnotes.conn.get_global("hidden_modules") add_home_page(bootinfo, doclist) add_allowed_pages(bootinfo) load_translations(bootinfo) load_country_and_currency(bootinfo, doclist) # ipinfo if webnotes.session["data"].get("ipinfo"): bootinfo["ipinfo"] = webnotes.session["data"]["ipinfo"] # add docs bootinfo["docs"] = doclist # plugins try: import startup.boot startup.boot.boot_session(bootinfo) except ImportError: pass from webnotes.model.utils import compress bootinfo["docs"] = compress(bootinfo["docs"]) return bootinfo
def build_page(page_name): if not webnotes.conn: webnotes.connect() sitemap_options = webnotes.doc("Website Sitemap", page_name).fields page_options = webnotes.doc("Website Sitemap Config", sitemap_options.get("website_sitemap_config")).fields.update({ "page_name":sitemap_options.page_name, "docname":sitemap_options.docname }) if not page_options: raise PageNotFoundError else: page_options["page_name"] = page_name basepath = webnotes.utils.get_base_path() no_cache = page_options.get("no_cache") # if generator, then load bean, pass arguments if page_options.get("page_or_generator")=="Generator": doctype = page_options.get("ref_doctype") obj = webnotes.get_obj(doctype, page_options["docname"], with_children=True) if hasattr(obj, 'get_context'): obj.get_context() context = webnotes._dict(obj.doc.fields) context["obj"] = obj else: # page context = webnotes._dict({ 'name': page_name }) if page_options.get("controller"): module = webnotes.get_module(page_options.get("controller")) if module and hasattr(module, "get_context"): context.update(module.get_context()) context.update(get_website_settings()) jenv = webnotes.get_jenv() context["base_template"] = jenv.get_template(webnotes.get_config().get("base_template")) template_name = page_options['template_path'] html = jenv.get_template(template_name).render(context) if not no_cache: webnotes.cache().set_value("page:" + page_name, html) return html
def __init__(self, user, resume=False): self.sid = webnotes.form_dict.get('sid') or webnotes.request.cookies.get('sid', 'Guest') self.user = user self.data = webnotes._dict({'data': webnotes._dict({})}) self.time_diff = None if resume: self.resume() else: self.start() # set local session webnotes.local.session = self.data # write out latest cookies webnotes.local.cookie_manager.set_cookies()
def get_bootinfo(): """build and return boot info""" bootinfo = webnotes._dict() doclist = [] # profile get_profile(bootinfo) # control panel cp = webnotes.model.doc.getsingle("Control Panel") # system info bootinfo["control_panel"] = webnotes._dict(cp.copy()) bootinfo["sysdefaults"] = webnotes.utils.get_defaults() bootinfo["server_date"] = webnotes.utils.nowdate() if webnotes.session["user"] != "Guest": bootinfo["user_info"] = get_fullnames() bootinfo["sid"] = webnotes.session["sid"] # home page add_home_page(bootinfo, doclist) add_allowed_pages(bootinfo) load_translations(bootinfo) load_country_and_currency(bootinfo, doclist) # ipinfo if webnotes.session["data"].get("ipinfo"): bootinfo["ipinfo"] = webnotes.session["data"]["ipinfo"] # add docs bootinfo["docs"] = doclist # plugins try: from startup import event_handlers if getattr(event_handlers, "boot_session", None): event_handlers.boot_session(bootinfo) except ImportError: pass from webnotes.model.utils import compress bootinfo["docs"] = compress(bootinfo["docs"]) return bootinfo
def insert_entries(self, opts, row): """Insert Stock Ledger Entries""" args = webnotes._dict({ "doctype": "Stock Ledger Entry", "item_code": row.item_code, "warehouse": row.warehouse, "posting_date": self.doc.posting_date, "posting_time": self.doc.posting_time, "voucher_type": self.doc.doctype, "voucher_no": self.doc.name, "company": self.doc.company, "is_cancelled": "No", "voucher_detail_no": row.voucher_detail_no }) args.update(opts) # create stock ledger entry sle_wrapper = webnotes.bean([args]) sle_wrapper.ignore_permissions = 1 sle_wrapper.insert() # update bin webnotes.get_obj('Warehouse', row.warehouse).update_bin(args) # append to entries self.entries.append(args)
def on_update(self, page_name=None): self.setup_generator() if self._website_config.condition_field: if not self.doc.fields.get(self._website_config.condition_field): # condition field failed, return remove_page(self.doc.fields.get(self._website_config.page_name_field)) return if not page_name: new_page_name = cleanup_page_name(self.get_page_title() \ if hasattr(self, "get_page_title") else (self.doc.title or self.doc.name)) self.check_if_page_name_is_unique(new_page_name) remove_page(self.doc.page_name) if self.doc.fields.get(self._website_config.page_name_field)!=new_page_name: webnotes.conn.set(self.doc, self._website_config.page_name_field, new_page_name) page_name = new_page_name add_to_sitemap(webnotes._dict({ "ref_doctype":self.doc.doctype, "docname": self.doc.name, "page_name": page_name, "link_name": self._website_config.name, "lastmod": webnotes.utils.get_datetime(self.doc.modified).strftime("%Y-%m-%d") }))
def get_country_info(country=None): data = get_all() data = webnotes._dict(data.get(country, {})) if not 'date_format' in data: data.date_format = "dd-mm-yyyy" return data
def execute(filters=None): if not filters: filters = {} stock_ledger_entries = get_stock_ledger_entries(filters) source = get_source_data(filters) item_sales_bom = get_item_sales_bom() columns = ["Delivery Note/Sales Invoice::120", "Posting Date:Date", "Posting Time", "Item Code:Link/Item", "Item Name", "Description", "Warehouse:Link/Warehouse", "Qty:Float", "Selling Rate:Currency", "Selling Amount:Currency", "Buying Amount:Currency", "Gross Profit:Currency", "Gross Profit %:Percent", "Project:Link/Project"] data = [] for row in source: selling_amount = flt(row.amount) buying_amount = get_buying_amount(row.item_code, row.warehouse, -1*row.qty, row.parenttype, row.name, row.item_row, stock_ledger_entries, item_sales_bom.get(row.parenttype, {}).get(row.name, webnotes._dict())) buying_amount = buying_amount > 0 and buying_amount or 0 if selling_amount: gross_profit = selling_amount - buying_amount gross_profit_percent = (gross_profit / selling_amount) * 100.0 else: gross_profit = gross_profit_percent = 0.0 name = """<a href="%s">%s</a>""" % ("/".join(["#Form", row.parenttype, row.name]), row.name) data.append([name, row.posting_date, row.posting_time, row.item_code, row.item_name, row.description, row.warehouse, row.qty, row.basic_rate, row.amount, buying_amount, gross_profit, gross_profit_percent, row.project]) return columns, data
def _get_basic_details(args, item_bean, warehouse_fieldname): item = item_bean.doc from webnotes.defaults import get_user_default_as_list user_default_warehouse_list = get_user_default_as_list('warehouse') user_default_warehouse = user_default_warehouse_list[0] \ if len(user_default_warehouse_list)==1 else "" out = webnotes._dict({ "item_code": item.name, "description": item.description_html or item.description, warehouse_fieldname: user_default_warehouse or item.default_warehouse \ or args.get(warehouse_fieldname), "income_account": item.default_income_account or args.income_account \ or webnotes.conn.get_value("Company", args.company, "default_income_account"), "expense_account": item.purchase_account or args.expense_account \ or webnotes.conn.get_value("Company", args.company, "default_expense_account"), "cost_center": item.default_sales_cost_center or args.cost_center, "qty": 1.0, "export_amount": 0.0, "amount": 0.0, "batch_no": None, "item_tax_rate": json.dumps(dict(([d.tax_type, d.tax_rate] for d in item_bean.doclist.get({"parentfield": "item_tax"})))), }) for fieldname in ("item_name", "item_group", "barcode", "brand", "stock_uom"): out[fieldname] = item.fields.get(fieldname) return out
def setup_account(args=None): # if webnotes.conn.sql("select name from tabCompany"): # webnotes.throw(_("Setup Already Complete!!")) if not args: args = webnotes.local.form_dict if isinstance(args, basestring): args = json.loads(args) args = webnotes._dict(args) update_profile_name(args) create_fiscal_year_and_company(args) set_defaults(args) create_territories() create_price_lists(args) create_feed_and_todo() create_email_digest() create_letter_head(args) create_taxes(args) create_items(args) create_customers(args) create_suppliers(args) webnotes.conn.set_value('Control Panel', None, 'home_page', 'desktop') webnotes.clear_cache() webnotes.conn.commit() # suppress msgprints webnotes.local.message_log = [] return "okay"
def get_requested_items(self): item_projected_qty = self.get_projected_qty() items_to_be_requested = webnotes._dict() for item, so_item_qty in self.item_dict.items(): requested_qty = 0 total_qty = sum([flt(d[0]) for d in so_item_qty]) if total_qty > item_projected_qty.get(item, 0): # shortage requested_qty = total_qty - item_projected_qty.get(item, 0) # consider minimum order qty requested_qty = requested_qty > flt(so_item_qty[0][3]) and \ requested_qty or flt(so_item_qty[0][3]) # distribute requested qty SO wise for item_details in so_item_qty: if requested_qty: sales_order = item_details[4] or "No Sales Order" if requested_qty <= item_details[0]: adjusted_qty = requested_qty else: adjusted_qty = item_details[0] items_to_be_requested.setdefault(item, {}).setdefault(sales_order, 0) items_to_be_requested[item][sales_order] += adjusted_qty requested_qty -= adjusted_qty else: break # requested qty >= total so qty, due to minimum order qty if requested_qty: items_to_be_requested.setdefault(item, {}).setdefault("No Sales Order", 0) items_to_be_requested[item]["No Sales Order"] += requested_qty return items_to_be_requested
def add_or_update_sitemap(self): page_name = self.get_page_name() existing_page_name = webnotes.conn.get_value("Website Sitemap", {"ref_doctype": self.doc.doctype, "docname": self.doc.name}) opts = webnotes._dict({ "page_or_generator": "Generator", "ref_doctype":self.doc.doctype, "docname": self.doc.name, "page_name": page_name, "link_name": self._website_config.name, "lastmod": webnotes.utils.get_datetime(self.doc.modified).strftime("%Y-%m-%d"), "parent_website_sitemap": self.doc.parent_website_sitemap, "page_title": self.get_page_title() \ if hasattr(self, "get_page_title") else (self.doc.title or self.doc.name) }) if self.meta.get_field("public_read"): opts.public_read = self.doc.public_read opts.public_write = self.doc.public_write else: opts.public_read = 1 if existing_page_name: if existing_page_name != page_name: webnotes.rename_doc("Website Sitemap", existing_page_name, page_name, ignore_permissions=True) update_sitemap(page_name, opts) else: add_to_sitemap(opts)
def add_calendar_event(self, opts=None, force=False): if not opts: opts = webnotes._dict() opts.description = "" if self.doc.customer: if self.doc.contact_person: opts.description = 'Contact '+cstr(self.doc.contact_person) else: opts.description = 'Contact customer '+cstr(self.doc.customer) elif self.doc.lead: if self.doc.contact_display: opts.description = 'Contact '+cstr(self.doc.contact_display) else: opts.description = 'Contact lead '+cstr(self.doc.lead) opts.subject = opts.description opts.description += '. By : ' + cstr(self.doc.contact_by) if self.doc.to_discuss: opts.description += ' To Discuss : ' + cstr(self.doc.to_discuss) super(DocType, self).add_calendar_event(opts, force)
def _get_basic_details(args, item_bean, warehouse_fieldname): item = item_bean.doc out = webnotes._dict({ "item_code": item.name, "description": item.description_html or item.description, warehouse_fieldname: item.default_warehouse or args.get(warehouse_fieldname), "income_account": item.default_income_account or args.income_account \ or webnotes.conn.get_value("Company", args.company, "default_income_account"), "expense_account": item.purchase_account or args.expense_account \ or webnotes.conn.get_value("Company", args.company, "default_expense_account"), "cost_center": item.default_sales_cost_center or args.cost_center, "qty": 1.0, "export_amount": 0.0, "amount": 0.0, "batch_no": None, "item_tax_rate": json.dumps(dict(([d.tax_type, d.tax_rate] for d in item_bean.doclist.get({"parentfield": "item_tax"})))), }) for fieldname in ("item_name", "item_group", "barcode", "brand", "stock_uom"): out[fieldname] = item.fields.get(fieldname) return out
def prepare_args(doctype, filters, fields, docstatus, group_by, order_by, with_childnames): webnotes.local.reportview_tables = get_tables(doctype, fields) load_doctypes() remove_user_tags(doctype, fields) conditions = build_conditions(doctype, fields, filters, docstatus) args = webnotes._dict() if with_childnames: for t in webnotes.local.reportview_tables: if t != "`tab" + doctype + "`": fields.append(t + ".name as '%s:name'" % t[4:-1]) # query dict args.tables = ', '.join(webnotes.local.reportview_tables) args.conditions = ' and '.join(conditions) args.fields = ', '.join(fields) args.order_by = order_by or webnotes.local.reportview_tables[0] + '.modified desc' args.group_by = group_by and (" group by " + group_by) or "" check_sort_by_table(args.order_by) return args
def setup_account(args=None): # if webnotes.conn.sql("select name from tabCompany"): # webnotes.throw(_("Setup Already Complete!!")) if not args: args = webnotes.local.form_dict if isinstance(args, basestring): args = json.loads(args) args = webnotes._dict(args) update_profile_name(args) create_fiscal_year_and_company(args) set_defaults(args) create_territories() # create_price_lists(args) create_feed_and_todo() import_core_docs() # create_email_digest() # create_letter_head(args) # create_taxes(args) # create_items(args) # create_customers(args) # create_suppliers(args) webnotes.conn.set_value('Control Panel', None, 'home_page', 'desktop') webnotes.clear_cache() webnotes.conn.commit() # suppress msgprints webnotes.local.message_log = [] exec_in_shell("""cp -r {path}/lib/public/datatable {path}/public/files """.format(path=get_base_path())) webnotes.conn.sql( "CREATE TABLE ack(ENCOUNTER_ID varchar(20),ACK varchar(20))") webnotes.conn.sql("commit()") return "okay"
def set_buying_amount(self, stock_ledger_entries=None): from stock.utils import get_buying_amount if not stock_ledger_entries: stock_ledger_entries = self.get_stock_ledger_entries() item_sales_bom = {} for d in self.doclist.get({"parentfield": "packing_details"}): new_d = webnotes._dict(d.fields.copy()) new_d.total_qty = -1 * d.qty item_sales_bom.setdefault(d.parent_item, []).append(new_d) if stock_ledger_entries: for item in self.doclist.get({"parentfield": self.fname}): if item.item_code in self.stock_items or \ (item_sales_bom and item_sales_bom.get(item.item_code)): buying_amount = get_buying_amount( item.item_code, item.warehouse, -1 * item.qty, self.doc.doctype, self.doc.name, item.name, stock_ledger_entries, item_sales_bom) item.buying_amount = buying_amount >= 0.01 and buying_amount or 0 webnotes.conn.set_value(item.doctype, item.name, "buying_amount", item.buying_amount)
# Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors # License: GNU General Public License v3. See license.txt from __future__ import unicode_literals import webnotes from setup.page.setup_wizard.test_setup_data import args from setup.page.setup_wizard.setup_wizard import setup_account if __name__ == "__main__": webnotes.connect() webnotes.local.form_dict = webnotes._dict(args) setup_account()
def __init__(self, filters=None): self.filters = webnotes._dict(filters or {}) self.filters.report_date = getdate(self.filters.report_date or nowdate()) self.age_as_on = getdate(nowdate()) \ if self.filters.report_date > getdate(nowdate()) \ else self.filters.report_date
def fmap(self): if not hasattr(self, "_fmap"): if self.doc.doctype in [ "Lead", "Quotation", "Sales Order", "Sales Invoice", "Delivery Note" ]: self._fmap = webnotes._dict({ "exchange_rate": "conversion_rate", "taxes_and_charges": "other_charges", "taxes_and_charges_master": "charge", "taxes_and_charges_total": "other_charges_total", "net_total_print": "net_total_print", "grand_total_print": "grand_total_export", "grand_total_in_words": "grand_total_in_words", "grand_total_in_words_print": "grand_total_in_words_print", "rounded_total_print": "rounded_total_export", "rounded_total_in_words": "in_words", "rounded_total_in_words_print": "in_words_export", "print_ref_rate": "ref_rate", "discount": "adj_rate", "print_rate": "export_rate", "print_amount": "export_amount", "ref_rate": "base_ref_rate", "rate": "basic_rate", "plc_exchange_rate": "plc_conversion_rate", "tax_calculation": "other_charges_calculation", "cost_center": "cost_center_other_charges", }) else: self._fmap = webnotes._dict({ "exchange_rate": "conversion_rate", "taxes_and_charges": "purchase_tax_details", "taxes_and_charges_master": "purchase_other_charges", "taxes_and_charges_total": "total_tax", "net_total_print": "net_total_import", "grand_total_print": "grand_total_import", "grand_total_in_words": "in_words", "grand_total_in_words_print": "in_words_import", "rounded_total_print": "rounded_total_print", "rounded_total_in_words": "rounded_total_in_words", "rounded_total_in_words_print": "rounded_total_in_words_print", "print_ref_rate": "import_ref_rate", "discount": "discount_rate", "print_rate": "import_rate", "print_amount": "import_amount", "ref_rate": "purchase_ref_rate", "rate": "purchase_rate", "valuation_tax_amount": "item_tax_amount" }) if self.doc.doctype == "Purchase Invoice": self._fmap.update({"rate": "rate"}) return self._fmap or webnotes._dict()
from __future__ import unicode_literals import webnotes, json import webnotes.model.doc import webnotes.model.doctype from webnotes.model.meta import get_table_fields from webnotes.model.doc import Document from webnotes.utils import cstr from webnotes.utils.datautils import UnicodeWriter, check_record, import_doc, getlink, cint, flt from webnotes import _ data_keys = webnotes._dict({ "data_separator": 'Start entering data below this line', "main_table": "Table:", "parent_table": "Parent Table:", "columns": "Column Name:", "doctype": "DocType:" }) @webnotes.whitelist() def get_doctypes(): return [ r[0] for r in webnotes.conn.sql("""select name from `tabDocType` where document_type = 'Master' or allow_import = 1""") ] @webnotes.whitelist() def get_doctype_options():
def setup(self, args=None): # overrride self.settings = args or webnotes._dict()
def write_static(): webnotes.local.session = webnotes._dict({"user": "******"}) pages = prepare_static_pages() write_docs(pages) prepare_docs()
def get_website_settings(): from webnotes.utils import get_request_site_address, encode, cint from urllib import quote all_top_items = webnotes.conn.sql("""\ select * from `tabTop Bar Item` where parent='Website Settings' and parentfield='top_bar_items' order by idx asc""", as_dict=1) top_items = [d for d in all_top_items if not d['parent_label']] # attach child items to top bar for d in all_top_items: if d['parent_label']: for t in top_items: if t['label'] == d['parent_label']: if not 'child_items' in t: t['child_items'] = [] t['child_items'].append(d) break context = webnotes._dict({ 'top_bar_items': top_items, 'footer_items': webnotes.conn.sql("""\ select * from `tabTop Bar Item` where parent='Website Settings' and parentfield='footer_items' order by idx asc""", as_dict=1), "webnotes": webnotes, "utils": webnotes.utils, "post_login": [{ "label": "Reset Password", "url": "update-password", "icon": "icon-key" }, { "label": "Logout", "url": "/?cmd=web_logout", "icon": "icon-signout" }] }) settings = webnotes.doc("Website Settings", "Website Settings") for k in [ "banner_html", "brand_html", "copyright", "twitter_share_via", "favicon", "facebook_share", "google_plus_one", "twitter_share", "linked_in_share", "disable_signup" ]: if k in settings.fields: context[k] = settings.fields.get(k) if settings.address: context["footer_address"] = settings.address for k in [ "facebook_share", "google_plus_one", "twitter_share", "linked_in_share", "disable_signup" ]: context[k] = cint(context.get(k) or 0) context.url = quote(str(get_request_site_address(full_address=True)), str("")) context.encoded_title = quote(encode(context.title or ""), str("")) try: import startup.webutils if hasattr(startup.webutils, "get_website_settings"): startup.webutils.get_website_settings(context) except: pass return context
def get_last_purchase_details(item_code, doc_name, conversion_rate=1.0): """returns last purchase details in stock uom""" # get last purchase order item details last_purchase_order = webnotes.conn.sql("""\ select po.name, po.transaction_date, po.conversion_rate, po_item.conversion_factor, po_item.purchase_ref_rate, po_item.discount_rate, po_item.purchase_rate from `tabPurchase Order` po, `tabPurchase Order Item` po_item where po.docstatus = 1 and po_item.item_code = %s and po.name != %s and po.name = po_item.parent order by po.transaction_date desc, po.name desc limit 1""", (item_code, doc_name), as_dict=1) # get last purchase receipt item details last_purchase_receipt = webnotes.conn.sql("""\ select pr.name, pr.posting_date, pr.posting_time, pr.conversion_rate, pr_item.conversion_factor, pr_item.purchase_ref_rate, pr_item.discount_rate, pr_item.purchase_rate from `tabPurchase Receipt` pr, `tabPurchase Receipt Item` pr_item where pr.docstatus = 1 and pr_item.item_code = %s and pr.name != %s and pr.name = pr_item.parent order by pr.posting_date desc, pr.posting_time desc, pr.name desc limit 1""", (item_code, doc_name), as_dict=1) purchase_order_date = getdate(last_purchase_order and last_purchase_order[0].transaction_date \ or "1900-01-01") purchase_receipt_date = getdate(last_purchase_receipt and \ last_purchase_receipt[0].posting_date or "1900-01-01") if (purchase_order_date > purchase_receipt_date) or \ (last_purchase_order and not last_purchase_receipt): # use purchase order last_purchase = last_purchase_order[0] purchase_date = purchase_order_date elif (purchase_receipt_date > purchase_order_date) or \ (last_purchase_receipt and not last_purchase_order): # use purchase receipt last_purchase = last_purchase_receipt[0] purchase_date = purchase_receipt_date else: return webnotes._dict() conversion_factor = flt(last_purchase.conversion_factor) out = webnotes._dict({ "purchase_ref_rate": flt(last_purchase.purchase_ref_rate) / conversion_factor, "purchase_rate": flt(last_purchase.purchase_rate) / conversion_factor, "discount_rate": flt(last_purchase.discount_rate), "purchase_date": purchase_date }) conversion_rate = flt(conversion_rate) or 1.0 out.update({ "import_ref_rate": out.purchase_ref_rate / conversion_rate, "import_rate": out.purchase_rate / conversion_rate, "rate": out.purchase_rate }) return out
def get_item_details(args): """ args = { "doctype": "", "docname": "", "item_code": "", "warehouse": None, "supplier": None, "transaction_date": None, "conversion_rate": 1.0 } """ if isinstance(args, basestring): args = json.loads(args) args = webnotes._dict(args) item_wrapper = webnotes.bean("Item", args.item_code) item = item_wrapper.doc from stock.utils import validate_end_of_life validate_end_of_life(item.name, item.end_of_life) # fetch basic values out = webnotes._dict() out.update({ "item_name": item.item_name, "item_group": item.item_group, "brand": item.brand, "description": item.description, "qty": 0, "stock_uom": item.stock_uom, "uom": item.stock_uom, "conversion_factor": 1.0, "warehouse": args.warehouse or item.default_warehouse, "item_tax_rate": json.dumps( dict( ([d.tax_type, d.tax_rate] for d in item_wrapper.doclist.get({"parentfield": "item_tax"}) ))), "batch_no": None, "expense_head": item.purchase_account, "cost_center": item.cost_center }) if args.supplier: item_supplier = item_wrapper.doclist.get({ "parentfield": "item_supplier_details", "supplier": args.supplier }) if item_supplier: out["supplier_part_no"] = item_supplier[0].supplier_part_no if out.warehouse: out.projected_qty = webnotes.conn.get_value("Bin", { "item_code": item.name, "warehouse": out.warehouse }, "projected_qty") if args.transaction_date and item.lead_time_days: out.schedule_date = out.lead_time_date = add_days( args.transaction_date, item.lead_time_days) # set zero out.purchase_ref_rate = out.discount_rate = out.purchase_rate = \ out.import_ref_rate = out.import_rate = 0.0 if args.doctype in [ "Purchase Order", "Purchase Invoice", "Purchase Receipt", "Supplier Quotation" ]: # try fetching from price list if args.price_list_name and args.price_list_currency: rates_as_per_price_list = get_rates_as_per_price_list( args, item_wrapper.doclist) if rates_as_per_price_list: out.update(rates_as_per_price_list) # if not found, fetch from last purchase transaction if not out.purchase_rate: last_purchase = get_last_purchase_details(item.name, args.docname, args.conversion_rate) if last_purchase: out.update(last_purchase) return out
def upload(): """upload data""" webnotes.mute_emails = True from webnotes.utils.datautils import read_csv_content_from_uploaded_file def bad_template(): webnotes.msgprint("Please do not change the rows above '%s'" % data_keys.data_separator, raise_exception=1) def check_data_length(): max_rows = 5000 if not data: webnotes.msgprint("No data found", raise_exception=True) elif len(data) > max_rows: webnotes.msgprint("Please upload only upto %d %ss at a time" % \ (max_rows, doctype), raise_exception=True) def get_start_row(): for i, row in enumerate(rows): if row and row[0] == data_keys.data_separator: return i + 1 bad_template() def get_header_row(key): for i, row in enumerate(header): if row and row[0] == key: return row return [] def filter_empty_columns(columns): empty_cols = filter(lambda x: x in ("", None), columns) if empty_cols: if columns[-1 * len(empty_cols):] == empty_cols: # filter empty columns if they exist at the end columns = columns[:-1 * len(empty_cols)] else: webnotes.msgprint(_( "Please make sure that there are no empty columns in the file." ), raise_exception=1) return columns # extra input params import json params = json.loads(webnotes.form_dict.get("params") or '{}') # header rows = read_csv_content_from_uploaded_file( params.get("ignore_encoding_errors")) start_row = get_start_row() header = rows[:start_row] data = rows[start_row:] doctype = get_header_row(data_keys.main_table)[1] columns = filter_empty_columns(get_header_row(data_keys.columns)[1:]) parenttype = get_header_row(data_keys.parent_table) if len(parenttype) > 1: parenttype = parenttype[1] parentfield = get_parent_field(doctype, parenttype) # allow limit rows to be uploaded check_data_length() webnotes.conn.begin() overwrite = params.get('overwrite') doctype_dl = webnotes.model.doctype.get(doctype) # delete child rows (if parenttype) if parenttype and overwrite: delete_child_rows(data, doctype) ret = [] error = False parent_list = [] for i, row in enumerate(data): # bypass empty rows if not row: continue row_idx = (i + 1) + start_row d = webnotes._dict(zip(columns, row[1:])) d['doctype'] = doctype try: check_record(d, parenttype, doctype_dl) if parenttype: # child doc doc = Document(doctype) doc.fields.update(d) if parenttype: doc.parenttype = parenttype doc.parentfield = parentfield doc.save() ret.append('Inserted row for %s at #%s' % (getlink(parenttype, doc.parent), unicode(doc.idx))) parent_list.append(doc.parent) else: ret.append( import_doc(d, doctype, overwrite, row_idx, params.get("_submit"))) except Exception, e: error = True err_msg = webnotes.message_log and "<br>".join( webnotes.message_log) or cstr(e) ret.append('Error for row (#%d) %s : %s' % (row_idx, len(row) > 1 and row[1] or "", err_msg)) webnotes.errprint(webnotes.getTraceback()) webnotes.message_log = []
def build_page(page_name): from jinja2 import Environment, FileSystemLoader from markdown2 import markdown if not webnotes.conn: webnotes.connect() sitemap = get_website_sitemap() page_options = sitemap.get(page_name) if not page_options: if page_name == "index": # page not found, try home page home_page = get_home_page() page_options = sitemap.get(home_page) if not page_options: raise PageNotFoundError page_options["page_name"] = home_page else: raise PageNotFoundError else: page_options["page_name"] = page_name basepath = webnotes.utils.get_base_path() module = None no_cache = False if page_options.get("controller"): module = webnotes.get_module(page_options["controller"]) no_cache = getattr(module, "no_cache", False) # if generator, then load bean, pass arguments if page_options.get("is_generator"): if not module: raise Exception("Generator controller not defined") name = webnotes.conn.get_value( module.doctype, {"page_name": page_options["page_name"]}) obj = webnotes.get_obj(module.doctype, name, with_children=True) if hasattr(obj, 'get_context'): obj.get_context() context = webnotes._dict(obj.doc.fields) context["obj"] = obj else: # page context = webnotes._dict({'name': page_name}) if module and hasattr(module, "get_context"): context.update(module.get_context()) context.update(get_website_settings()) jenv = Environment(loader=FileSystemLoader(basepath)) jenv.filters["markdown"] = markdown context["base_template"] = jenv.get_template( webnotes.get_config().get("base_template")) template_name = page_options['template'] html = jenv.get_template(template_name).render(context) if not no_cache: webnotes.cache().set_value("page:" + page_name, html) return html
def execute(filters=None): if not filters: filters = {} employee_filters = filters.get("company") and \ [["Employee", "company", "=", filters.get("company")]] or None employees = runreport(doctype="Employee", fields=["name", "employee_name", "department"], filters=employee_filters) leave_types = webnotes.conn.sql_list("select name from `tabLeave Type`") if filters.get("fiscal_year"): fiscal_years = [filters["fiscal_year"]] else: fiscal_years = webnotes.conn.sql_list( "select name from `tabFiscal Year` order by name desc") employee_in = '", "'.join([e.name for e in employees]) allocations = webnotes.conn.sql( """select employee, fiscal_year, leave_type, total_leaves_allocated from `tabLeave Allocation` where docstatus=1 and employee in ("%s")""" % employee_in, as_dict=True) applications = webnotes.conn.sql( """select employee, fiscal_year, leave_type, SUM(total_leave_days) as leaves from `tabLeave Application` where status="Approved" and docstatus = 1 and employee in ("%s") group by employee, fiscal_year, leave_type""" % employee_in, as_dict=True) columns = [ "Fiscal Year", "Employee:Link/Employee:150", "Employee Name::200", "Department::150" ] for leave_type in leave_types: columns.append(leave_type + " Allocated:Float") columns.append(leave_type + " Taken:Float") columns.append(leave_type + " Balance:Float") data = {} for d in allocations: data.setdefault((d.fiscal_year, d.employee, d.leave_type), webnotes._dict()).allocation = d.total_leaves_allocated for d in applications: data.setdefault((d.fiscal_year, d.employee, d.leave_type), webnotes._dict()).leaves = d.leaves result = [] for fiscal_year in fiscal_years: for employee in employees: row = [ fiscal_year, employee.name, employee.employee_name, employee.department ] result.append(row) for leave_type in leave_types: tmp = data.get((fiscal_year, employee.name, leave_type), webnotes._dict()) row.append(tmp.allocation or 0) row.append(tmp.leaves or 0) row.append((tmp.allocation or 0) - (tmp.leaves or 0)) return columns, result
def get_data(rows, company_abbr): start_row = 0 data = [] start_row_idx = 0 for i in xrange(len(rows)): r = rows[i] if r[0]: if start_row and i >= start_row: if not start_row_idx: start_row_idx = i d, acc_dict = webnotes._dict(), webnotes._dict() for cidx in xrange(len(columns)): d[columns[cidx]] = r[cidx] if accounts: total_debit = total_credit = 0 for acc_idx in xrange(len(accounts)): col_idx = len(columns) + acc_idx if flt(r[col_idx]) != 0: if not acc_dict.get(accounts[acc_idx]): acc_dict[accounts[acc_idx]] = 0 acc_dict[accounts[acc_idx]] += flt(r[col_idx]) if flt(r[col_idx]) > 0: total_debit += flt(r[col_idx]) else: total_credit += abs(flt(r[col_idx])) d['total_debit'] = total_debit d['total_credit'] = total_credit data.append([d, acc_dict]) if r[0] == "--------Data----------": start_row = i + 2 # check for empty columns empty_columns = [ j + 1 for j, c in enumerate(rows[i + 1]) if not c ] if empty_columns: raise Exception, """Column No(s). %s %s empty. \ Please remove them and try again.""" % (comma_and(empty_columns), len(empty_columns) == 1 and "is" or "are") columns = [ c.replace(" ", "_").lower() for c in rows[i + 1] if not c.endswith(" - " + company_abbr) ] accounts = [ c for c in rows[i + 1] if c.endswith(" - " + company_abbr) ] if accounts and (len(columns) != rows[i + 1].index( accounts[0])): raise Exception, _("""All account columns should be after \ standard columns and on the right. If you entered it properly, next probable reason \ could be wrong account name. Please rectify it in the file and try again.""") return data, start_row_idx
# Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors # License: GNU General Public License v3. See license.txt import webnotes, os, datetime import webnotes.utils from webnotes.utils import random_string from webnotes.widgets import query_report import random import json webnotes.session = webnotes._dict({"user": "******"}) from core.page.data_import_tool.data_import_tool import upload # fix price list # fix fiscal year company = "Wind Power LLC" company_abbr = "WP" country = "United States" currency = "USD" time_zone = "America/New_York" start_date = '2013-01-01' bank_name = "Citibank" runs_for = None prob = { "default": { "make": 0.6, "qty": (1, 5) }, "Sales Order": { "make": 0.4,
# GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from __future__ import unicode_literals import os import conf import webnotes from webnotes.utils import cstr page_map = { 'Web Page': webnotes._dict({ "template": 'html/web_page.html', "condition_field": "published" }), 'Blog': webnotes._dict({ "template": 'html/blog_page.html', "condition_field": "published", }), 'Item': webnotes._dict({ "template": 'html/product_page.html', "condition_field": "show_in_website", }), 'Item Group': webnotes._dict({ "template": "html/product_group.html", "condition_field": "show_in_website"
from __future__ import unicode_literals import webnotes import webnotes.model.doc import webnotes.model.doctype from webnotes.model.doc import Document from webnotes.utils import cstr from webnotes.utils.datautils import UnicodeWriter, check_record, import_doc, getlink from webnotes import _ data_keys = webnotes._dict({ "data_separator": 'Start entering data below this line', "main_table": "Table:", "parent_table": "Parent Table:", "columns": "Column Name:" }) @webnotes.whitelist() def get_doctypes(): return [ r[0] for r in webnotes.conn.sql("""select name from `tabDocType` where document_type = 'Master' or allow_import = 1""") ] @webnotes.whitelist() def get_doctype_options(): doctype = webnotes.form_dict['doctype'] return [doctype] + filter(None, map(lambda d: \ d.doctype=='DocField' and d.fieldtype=='Table' and d.options or None,
def update_template_args(page_name, args): from webnotes.utils import get_request_site_address from urllib import quote all_top_items = webnotes.conn.sql("""\ select * from `tabTop Bar Item` where parent='Website Settings' and parentfield='top_bar_items' order by idx asc""", as_dict=1) top_items = [d for d in all_top_items if not d['parent_label']] # attach child items to top bar for d in all_top_items: if d['parent_label']: for t in top_items: if t['label'] == d['parent_label']: if not 'child_items' in t: t['child_items'] = [] t['child_items'].append(d) break ret = webnotes._dict({ 'top_bar_items': top_items, 'footer_items': webnotes.conn.sql("""\ select * from `tabTop Bar Item` where parent='Website Settings' and parentfield='footer_items' order by idx asc""", as_dict=1), 'int': int, "webnotes": webnotes, "utils": webnotes.utils }) args.update(ret) settings = webnotes.doc("Website Settings", "Website Settings") for k in [ "banner_html", "brand_html", "copyright", "address", "twitter_share_via", "favicon", "facebook_share", "google_plus_one", "twitter_share", "linked_in_share", "disable_signup" ]: if k in settings.fields: args[k] = settings.fields.get(k) for k in [ "facebook_share", "google_plus_one", "twitter_share", "linked_in_share", "disable_signup" ]: args[k] = cint(args.get(k) or 0) args.url = quote(str(get_request_site_address(full_address=True)), str("")) args.encoded_title = quote(encode(args.title or ""), str("")) args.shopping_cart_enabled = cint( webnotes.conn.get_default("shopping_cart_enabled")) return args
def update_template_args(page_name, args): from webnotes.utils import get_request_site_address from urllib import quote all_top_items = webnotes.conn.sql("""\ select * from `tabTop Bar Item` where parent='Website Settings' and parentfield='top_bar_items' order by idx asc""", as_dict=1) top_items = [d for d in all_top_items if not d['parent_label']] # attach child items to top bar for d in all_top_items: if d['parent_label']: for t in top_items: if t['label'] == d['parent_label']: if not 'child_items' in t: t['child_items'] = [] t['child_items'].append(d) break if top_items and ("products" in [d.url.split(".")[0] for d in top_items if d.url]): # product categories products = webnotes.conn.sql("""select t1.item_group as label, t2.page_name as url, ifnull(t1.indent,0) as indent from `tabWebsite Product Category` t1, `tabItem Group` t2 where t1.item_group = t2.name and ifnull(t2.show_in_website,0)=1 order by t1.idx""", as_dict=1) products_item = filter( lambda d: d.url and d.url.split(".")[0] == "products", top_items)[0] products_item.child_items = products ret = webnotes._dict({ 'top_bar_items': top_items, 'footer_items': webnotes.conn.sql("""\ select * from `tabTop Bar Item` where parent='Website Settings' and parentfield='footer_items' order by idx asc""", as_dict=1), 'int': int, "webnotes": webnotes, "utils": webnotes.utils }) args.update(ret) settings = webnotes.doc("Website Settings", "Website Settings") for k in [ "banner_html", "brand_html", "copyright", "address", "twitter_share_via", "favicon", "facebook_share", "google_plus_one", "twitter_share", "linked_in_share", "disable_signup" ]: if k in settings.fields: args[k] = settings.fields.get(k) for k in [ "facebook_share", "google_plus_one", "twitter_share", "linked_in_share", "disable_signup" ]: args[k] = cint(args.get(k) or 0) args.url = quote(str(get_request_site_address(full_address=True)), str("")) args.encoded_title = quote(encode(args.title or ""), str("")) return args
def update_entries_after(args, verbose=1): """ update valution rate and qty after transaction from the current time-bucket onwards args = { "item_code": "ABC", "warehouse": "XYZ", "posting_date": "2012-12-12", "posting_time": "12:00" } """ if not _exceptions: webnotes.local.stockledger_exceptions = [] previous_sle = get_sle_before_datetime(args) qty_after_transaction = flt(previous_sle.get("qty_after_transaction")) valuation_rate = flt(previous_sle.get("valuation_rate")) stock_queue = json.loads(previous_sle.get("stock_queue") or "[]") stock_value = flt(previous_sle.get("stock_value")) prev_stock_value = flt(previous_sle.get("stock_value")) entries_to_fix = get_sle_after_datetime(previous_sle or \ {"item_code": args["item_code"], "warehouse": args["warehouse"]}, for_update=True) valuation_method = get_valuation_method(args["item_code"]) stock_value_difference = 0.0 for sle in entries_to_fix: if sle.serial_no or not cint( webnotes.conn.get_default("allow_negative_stock")): # validate negative stock for serialized items, fifo valuation # or when negative stock is not allowed for moving average if not validate_negative_stock(qty_after_transaction, sle): qty_after_transaction += flt(sle.actual_qty) continue if sle.serial_no: valuation_rate = get_serialized_values(qty_after_transaction, sle, valuation_rate) elif valuation_method == "Moving Average": valuation_rate = get_moving_average_values(qty_after_transaction, sle, valuation_rate) else: valuation_rate = get_fifo_values(qty_after_transaction, sle, stock_queue) qty_after_transaction += flt(sle.actual_qty) # get stock value if sle.serial_no: stock_value = qty_after_transaction * valuation_rate elif valuation_method == "Moving Average": stock_value = (qty_after_transaction > 0) and \ (qty_after_transaction * valuation_rate) or 0 else: stock_value = sum( (flt(batch[0]) * flt(batch[1]) for batch in stock_queue)) # rounding as per precision from webnotes.model.meta import get_field_precision meta = webnotes.get_doctype("Stock Ledger Entry") stock_value = flt( stock_value, get_field_precision(meta.get_field("stock_value"), webnotes._dict({"fields": sle}))) stock_value_difference = stock_value - prev_stock_value prev_stock_value = stock_value # update current sle webnotes.conn.sql( """update `tabStock Ledger Entry` set qty_after_transaction=%s, valuation_rate=%s, stock_queue=%s, stock_value=%s, stock_value_difference=%s where name=%s""", (qty_after_transaction, valuation_rate, json.dumps(stock_queue), stock_value, stock_value_difference, sle.name)) if _exceptions: _raise_exceptions(args, verbose) # update bin if not webnotes.conn.exists({ "doctype": "Bin", "item_code": args["item_code"], "warehouse": args["warehouse"] }): bin_wrapper = webnotes.bean([{ "doctype": "Bin", "item_code": args["item_code"], "warehouse": args["warehouse"], }]) bin_wrapper.ignore_permissions = 1 bin_wrapper.insert() webnotes.conn.sql( """update `tabBin` set valuation_rate=%s, actual_qty=%s, stock_value=%s, projected_qty = (actual_qty + indented_qty + ordered_qty + planned_qty - reserved_qty) where item_code=%s and warehouse=%s""", (valuation_rate, qty_after_transaction, stock_value, args["item_code"], args["warehouse"]))
def notify(self, args): args = webnotes._dict(args) from core.page.messages.messages import post post({"txt": args.message, "contact": args.message_to, "subject": args.subject, "notify": cint(self.doc.follow_via_email)})
def get_bootinfo(): """build and return boot info""" bootinfo = webnotes._dict() doclist = [] # profile get_profile(bootinfo) # control panel cp = webnotes.model.doc.getsingle('Control Panel') # system info bootinfo['control_panel'] = webnotes._dict(cp.copy()) bootinfo['sysdefaults'] = webnotes.defaults.get_defaults() bootinfo['server_date'] = webnotes.utils.nowdate() bootinfo["send_print_in_body_and_attachment"] = webnotes.conn.get_value( "Email Settings", None, "send_print_in_body_and_attachment") if webnotes.session['user'] != 'Guest': bootinfo['user_info'] = get_fullnames() bootinfo['sid'] = webnotes.session['sid'] # home page bootinfo.modules = webnotes.get_config().modules bootinfo.hidden_modules = webnotes.conn.get_global("hidden_modules") bootinfo.doctype_icons = dict( webnotes.conn.sql("""select name, icon from tabDocType where ifnull(icon,'')!=''""")) bootinfo.doctype_icons.update( dict( webnotes.conn.sql("""select name, icon from tabPage where ifnull(icon,'')!=''"""))) add_home_page(bootinfo, doclist) add_allowed_pages(bootinfo) load_translations(bootinfo) load_conf_settings(bootinfo) # ipinfo if webnotes.session['data'].get('ipinfo'): bootinfo['ipinfo'] = webnotes.session['data']['ipinfo'] # add docs bootinfo['docs'] = doclist # plugins try: import startup.boot startup.boot.boot_session(bootinfo) except ImportError: pass from webnotes.model.utils import compress bootinfo['docs'] = compress(bootinfo['docs']) # deal with __slots__ in lang if bootinfo.lang: bootinfo.lang = unicode(bootinfo.lang) bootinfo.metadata_version = webnotes.cache().get_value("metadata_version") if not bootinfo.metadata_version: bootinfo.metadata_version = webnotes.reset_metadata_version() return bootinfo
def get_item_list(self): il = [] for d in self.doclist.get({"parentfield": self.fname}): reserved_warehouse = "" reserved_qty_for_main_item = 0 if self.doc.doctype == "Sales Order": if (webnotes.conn.get_value("Item", d.item_code, "is_stock_item") == 'Yes' or self.has_sales_bom( d.item_code)) and not d.reserved_warehouse: webnotes.throw( _("Please enter Reserved Warehouse for item ") + d.item_code + _(" as it is stock Item or packing item")) reserved_warehouse = d.reserved_warehouse if flt(d.qty) > flt(d.delivered_qty): reserved_qty_for_main_item = flt(d.qty) - flt( d.delivered_qty) if self.doc.doctype == "Delivery Note" and d.against_sales_order: # if SO qty is 10 and there is tolerance of 20%, then it will allow DN of 12. # But in this case reserved qty should only be reduced by 10 and not 12 already_delivered_qty = self.get_already_delivered_qty( self.doc.name, d.against_sales_order, d.prevdoc_detail_docname) so_qty, reserved_warehouse = self.get_so_qty_and_warehouse( d.prevdoc_detail_docname) if already_delivered_qty + d.qty > so_qty: reserved_qty_for_main_item = -(so_qty - already_delivered_qty) else: reserved_qty_for_main_item = -flt(d.qty) if self.has_sales_bom(d.item_code): for p in self.doclist.get({"parentfield": "packing_details"}): if p.parent_detail_docname == d.name and p.parent_item == d.item_code: # the packing details table's qty is already multiplied with parent's qty il.append( webnotes._dict({ 'warehouse': p.warehouse, 'reserved_warehouse': reserved_warehouse, 'item_code': p.item_code, 'qty': flt(p.qty), 'reserved_qty': (flt(p.qty) / flt(d.qty)) * reserved_qty_for_main_item, 'uom': p.uom, 'batch_no': cstr(p.batch_no).strip(), 'serial_no': cstr(p.serial_no).strip(), 'name': d.name })) else: il.append( webnotes._dict({ 'warehouse': d.warehouse, 'reserved_warehouse': reserved_warehouse, 'item_code': d.item_code, 'qty': d.qty, 'reserved_qty': reserved_qty_for_main_item, 'uom': d.stock_uom, 'batch_no': cstr(d.batch_no).strip(), 'serial_no': cstr(d.serial_no).strip(), 'name': d.name })) return il