def save_entries(gl_map, cancel, adv_adj, update_outstanding): total_debit = total_credit = 0.0 def _swap(gle): gle.debit, gle.credit = abs(flt(gle.credit)), abs(flt(gle.debit)) for entry in gl_map: gle = Document('GL Entry', fielddata=entry) # toggle debit, credit if negative entry if flt(gle.debit) < 0 or flt(gle.credit) < 0: _swap(gle) # toggled debit/credit in two separate condition because # both should be executed at the # time of cancellation when there is negative amount (tax discount) if cancel: _swap(gle) gle_obj = webnotes.get_obj(doc=gle) # validate except on_cancel if not cancel: gle_obj.validate() # save gle.save(1) gle_obj.on_update(adv_adj, cancel, update_outstanding) # update total debit / credit total_debit += flt(gle.debit) total_credit += flt(gle.credit) # print gle.account, gle.debit, gle.credit, total_debit, total_credit if not cancel: validate_total_debit_credit(total_debit, total_credit)
def validate_incoming(self): """ Checks support ticket email settings """ if self.doc.sync_support_mails and self.doc.support_host: from webnotes.utils.email_lib.receive import POP3Mailbox from webnotes.model.doc import Document import _socket, poplib inc_email = Document('Incoming Email Settings') inc_email.host = self.doc.support_host.encode('utf-8') inc_email.use_ssl = self.doc.support_use_ssl try: inc_email.username = self.doc.support_username.encode('utf-8') inc_email.password = self.doc.support_password.encode('utf-8') except AttributeError, e: webnotes.msgprint('User Name or Support Password missing. Please enter and try again.') webnotes.msgprint(e) pop_mb = POP3Mailbox(inc_email) try: pop_mb.connect() except _socket.error, e: # Invalid mail server -- due to refusing connection webnotes.msgprint('Invalid POP3 Mail Server. Please rectify and try again.') webnotes.msgprint(e)
def make_item_group_active(self): """show item group in website""" if self.doc.published: from webnotes.model.doc import Document ig = Document('Item Group', self.doc.item_group) ig.show_in_website = 1 ig.save()
def update_warranty_amc_history(self, submit=1): if self.doc.order_type in ["AMC", "OTS (One Time Service)"]: sr_list = [] if submit: for d in getlist(self.doclist, "service_order_details"): sr = Document("Serial No", d.serial_no) child = addchild(sr, "warranty_amc_history", "Warranty AMC History", 0) child.from_date = d.start_date child.to_date = d.end_date child.status = (self.doc.order_type == "AMC") and "Under AMC" or "OTS (One Time Service)" child.against_doctype = self.doc.doctype child.against_docname = self.doc.name child.customer = self.doc.customer child.territory = self.doc.territory child.save() sr.warranty_amc_status = (self.doc.order_type == "AMC") and "Under AMC" or "OTS (One Time Service)" sr.amc_expiry_date = d.end_date sr.save() sr_list.append(d.serial_no) else: sql( "delete from `tabWarranty AMC History` where against_doctype = %s and against_docname = %s", (self.doc.doctype, self.doc.name), ) for d in getlist(self.doclist, "service_order_details"): sql("update `tabSerial No` set amc_expiry_date = '' where name = '%s'" % (d.serial_no)) sr_list.append(d.serial_no) self.update_serial_no_warranty_amc_status(serial_no_list=sr_list)
def update_warranty_amc_history(self, submit = 1): if self.doc.order_type in ['AMC', 'OTS (One Time Service)']: sr_list = [] if submit: for d in getlist(self.doclist, 'service_order_details'): sr = Document('Serial No', d.serial_no) child = addchild(sr, 'warranty_amc_history', 'Warranty AMC History', 0) child.from_date = d.start_date child.to_date = d.end_date child.status = (self.doc.order_type == 'AMC') and 'Under AMC' or 'OTS (One Time Service)' child.against_doctype = self.doc.doctype child.against_docname = self.doc.name child.customer = self.doc.customer child.territory = self.doc.territory child.save() sr.warranty_amc_status = (self.doc.order_type == 'AMC') and 'Under AMC' or 'OTS (One Time Service)' sr.amc_expiry_date = d.end_date sr.save() sr_list.append(d.serial_no) else: sql("delete from `tabWarranty AMC History` where against_doctype = %s and against_docname = %s", (self.doc.doctype, self.doc.name)) for d in getlist(self.doclist, 'service_order_details'): sql("update `tabSerial No` set amc_expiry_date = '' where name = '%s'" % (d.serial_no)) sr_list.append(d.serial_no) self.update_serial_no_warranty_amc_status(serial_no_list = sr_list)
def getchildren(name, childtype, field='', parenttype='', from_doctype=0, prefix='tab'): import webnotes from webnotes.model.doclist import DocList condition = "" values = [] if field: condition += ' and parentfield=%s ' values.append(field) if parenttype: condition += ' and parenttype=%s ' values.append(parenttype) dataset = webnotes.conn.sql("""select * from `%s%s` where parent=%s %s order by idx""" \ % (prefix, childtype, "%s", condition), tuple([name]+values)) desc = webnotes.conn.get_description() l = DocList() for i in dataset: d = Document() d.doctype = childtype d._load_values(i, desc) l.append(d) return l
def save_file(fname, content, module=None): from webnotes.model.doc import Document from filecmp import cmp check_max_file_size(content) new_fname = write_file(content) # some browsers return the full path if '\\' in fname: fname = fname.split('\\')[-1] if '/' in fname: fname = fname.split('/')[-1] # we use - for versions, so remove them from the name! fname = fname.replace('-', '') fpath = os.path.join(get_files_path(), fname) if os.path.exists(fpath) and cmp(fpath, new_fname): # remove new file, already exists! os.remove(new_fname) return fname else: # generate the ID (?) f = Document('File Data') f.file_name = fname f.save(1) # rename new file os.rename(new_fname, os.path.join(get_files_path(), f.name)) return f.name
def make_feed(feedtype, doctype, name, owner, subject, color): "makes a new Feed record" #msgprint(subject) from webnotes.model.doc import Document from webnotes.utils import get_fullname if feedtype in ('Login', 'Comment', 'Assignment'): # delete old login, comment feed webnotes.conn.sql("""delete from tabFeed where datediff(curdate(), creation) > 7 and doc_type in ('Comment', 'Login', 'Assignment')""") else: # one feed per item webnotes.conn.sql("""delete from tabFeed where doc_type=%s and doc_name=%s and ifnull(feed_type,'') != 'Comment'""", (doctype, name)) f = Document('Feed') f.owner = owner f.feed_type = feedtype f.doc_type = doctype f.doc_name = name f.subject = subject f.color = color f.full_name = get_fullname(owner) f.save()
def load_data(): test_purchase_receipt.load_data() webnotes.insert({"doctype": "Account", "account_name": "Cost for Goods Sold", "parent_account": "Expenses - %s" % abbr, "company": company, "group_or_ledger": "Ledger"}) webnotes.insert({"doctype": "Account", "account_name": "Excise Duty", "parent_account": "_Test Tax Assets - %s" % abbr, "company": company, "group_or_ledger": "Ledger"}) webnotes.insert({"doctype": "Account", "account_name": "Education Cess", "parent_account": "_Test Tax Assets - %s" % abbr, "company": company, "group_or_ledger": "Ledger"}) webnotes.insert({"doctype": "Account", "account_name": "S&H Education Cess", "parent_account": "_Test Tax Assets - %s" % abbr, "company": company, "group_or_ledger": "Ledger"}) webnotes.insert({"doctype": "Account", "account_name": "CST", "parent_account": "Direct Expenses - %s" % abbr, "company": company, "group_or_ledger": "Ledger"}) webnotes.insert({"doctype": "Account", "account_name": "Discount", "parent_account": "Direct Expenses - %s" % abbr, "company": company, "group_or_ledger": "Ledger"}) from webnotes.model.doc import Document item = Document("Item", "Home Desktop 100") # excise duty item_tax = item.addchild("item_tax", "Item Tax") item_tax.tax_type = "Excise Duty - %s" % abbr item_tax.tax_rate = 10 item_tax.save()
def addchild(self, fieldname, childtype = '', doclist=None): """ Returns a child record of the give `childtype`. * if local is set, it does not save the record * if doclist is passed, it append the record to the doclist """ from webnotes.model.doc import Document d = Document() d.parent = self.name d.parenttype = self.doctype d.parentfield = fieldname d.doctype = childtype d.docstatus = 0; d.name = '' d.owner = webnotes.session['user'] d.fields['__islocal'] = 1 # for Client to identify unsaved doc if doclist != None: doclist.append(d) if doclist: d.idx = max([(d.idx or 0) for d in doclist if d.doctype==childtype]) + 1 return d
def create_production_order(self,company, pp_items): """Create production order. Called from Production Planning Tool""" default_values = { 'posting_date' : nowdate(), 'origin' : 'MRP', 'wip_warehouse' : '', 'fg_warehouse' : '', 'status' : 'Draft', 'company' : company, 'fiscal_year' : get_defaults()['fiscal_year'] } pro_list = [] for d in pp_items: pro_doc = Document('Production Order') for key in d.keys(): pro_doc.fields[key] = d[key] for key in default_values: pro_doc.fields[key] = default_values[key] pro_doc.save(new = 1) pro_list.append(pro_doc.name) return pro_list
def update_warranty_amc_history(self, submit = 1): if submit: for d in getlist(self.doclist, 'delivery_note_details'): if d.serial_no: serial_nos = self.get_sr_no_list(d.serial_no) for s in serial_nos: sr = Document('Serial No', s) child = addchild(sr, 'warranty_amc_history', 'Warranty AMC History', 0) child.from_date = self.doc.transaction_date child.to_date = d.warranty_expiry_date child.status = 'Under Warranty' child.against_doctype = self.doc.doctype child.against_docname = self.doc.name child.customer = self.doc.customer child.territory = self.doc.territory child.save() sr.warranty_amc_status = 'Under Warranty' sr.warranty_expiry_date = d.warranty_expiry_date sr.save() else: sql("delete from `tabWarranty AMC History` where against_doctype = %s and against_docname = %s", (self.doc.doctype, self.doc.name)) sr_list = [] for d in getlist(self.doclist, 'service_order_details'): if d.serial_no: serial_nos = self.get_sr_no_list(d.serial_no) for s in serial_nos: sql("update `tabSerial No` set warranty_expiry_date = '' where name = '%s'" % (s)) sr_list.append(s) self.update_serial_no_warranty_amc_status(serial_no_list = sr_list)
def create_production_order(self,company, fy, pp_detail = '', pro_detail = ''): pro_lbl = {'production_item': 0, 'description': 1, 'qty' : 2, 'stock_uom' : 3, 'bom_no': 4, 'consider_sa_items': 5} default_values = { 'transaction_date' : now(), 'origin' : pp_detail and 'MRP' or 'Direct', 'wip_warehouse' : 'MB1-Stores', 'status' : 'Draft', 'company' : company, 'fiscal_year' : fy } pro_list, count = pp_detail and pp_detail or pro_detail, 0 while (count < len(pro_list)): pro_doc = Document('Production Order') for key in pro_lbl.keys(): pro_doc.fields[key] = pro_list[count][pro_lbl[key]] for key in default_values: pro_doc.fields[key] = default_values[key] pro_doc.save(new = 1) pro_list[count] = pro_doc.name # This was for adding raw materials in pro detail and get sa items #sa_list = get_obj('Porduction Order', pro_doc.name, with_children = 1).get_purchase_item( get_sa_items = 1, add_child= 1) #for sa_item in sa_list: # pro_list.append(sa_item) count = count + 1 return pro_list
def create_doc(data): from webnotes.model.doc import Document d = Document(data["doctype"]) d.fields.update(data) d.save() print "Created %(doctype)s %(name)s" % d.fields
def create_child(self): from datetime import datetime # date_a=cstr(datetime.combine(datetime.strptime(self.doc.encounter_date,'%Y-%m-%d').date(),datetime.strptime(self.doc.start_time,'%H:%M').time())) # date_b=cstr(datetime.combine(datetime.strptime(self.doc.encounter_date,'%Y-%m-%d').date(),datetime.strptime(self.doc.end_time,'%H:%M').time())) if self.doc.appointment_slot: webnotes.errprint([self.doc.start_time]) check_confirmed=webnotes.conn.sql("select true from `tabSlot Child` where slot='"+self.doc.appointment_slot+"' and modality='"+self.doc.encounter+"' and study='"+self.doc.study+"' and date_format(start_time,'%Y-%m-%d %H:%M')=date_format('"+date_a+"','%Y-%m-%d %H:%M') and date_format(end_time,'%Y-%m-%d %H:%M')=date_format('"+date_b+"','%Y-%m-%d %H:%M') and status='Confirm'",debug=1) webnotes.errprint(check_confirmed) if not check_confirmed: check_status=webnotes.conn.sql("select case when count(*)<2 then true else false end from `tabSlot Child` where slot='"+self.doc.appointment_slot+"' and modality='"+self.doc.encounter+"' and study='"+self.doc.study+"' and date_format(start_time,'%Y-%m-%d %H:%M')=date_format('"+date_a+"','%Y-%m-%d %H:%M') and date_format(end_time,'%Y-%m-%d %H:%M')=date_format('"+date_b+"','%Y-%m-%d %H:%M') and status<>'Cancel'",as_list=1) webnotes.errprint(check_status[0][0]) if check_status[0][0]==1: d=Document("Slot Child") d.slot=self.doc.appointment_slot d.modality=self.doc.encounter d.study=self.doc.study d.status='Waiting' d.encounter=self.doc.name d.start_time=date_a d.end_time=date_b d.save() self.make_event(d.name) self.doc.slot=d.name else: webnotes.msgprint("Selected slot is not available",raise_exception=1) else: webnotes.msgprint("Selected slot is not available",raise_exception=1)
def make_single_entry(self,parent,d,le_map,cancel, merge_entries): if self.get_val(le_map['account'], d, parent) and \ (self.get_val(le_map['debit'], d, parent) \ or self.get_val(le_map['credit'], d, parent)): flist = ['account', 'cost_center', 'against', 'debit', 'credit', 'remarks', 'voucher_type', 'voucher_no', 'posting_date', 'fiscal_year', 'against_voucher', 'against_voucher_type', 'company', 'is_opening', 'aging_date'] # Check budget before gl entry #check budget only if account is expense account is_expense_acct = webnotes.conn.sql("""select name from tabAccount where is_pl_account='Yes' and debit_or_credit='Debit' and name=%s""",self.get_val(le_map['account'], d, parent)) if is_expense_acct and self.get_val(le_map['cost_center'], d, parent): get_obj('Budget Control').check_budget([self.get_val(le_map[k], d, parent) for k in flist if k in ['account', 'cost_center', 'debit', 'credit', 'posting_date', 'fiscal_year', 'company']],cancel) # Create new GL entry object and map values le = Document('GL Entry') for k in flist: le.fields[k] = self.get_val(le_map[k], d, parent) # if there is already an entry in this account then just add it to that entry same_head = self.check_if_in_list(le) if same_head and merge_entries: same_head = same_head[0] same_head.debit = flt(same_head.debit) + flt(le.debit) same_head.credit = flt(same_head.credit) + flt(le.credit) else: self.entries.append(le)
def import_docs(docs = []): from webnotes.model.doc import Document import webnotes.model.code doc_list = {} created_docs = [] already_exists = [] out, tmp ="", "" for d in docs: cur_doc = Document(fielddata = d) if not cur_doc.parent in already_exists: # parent should not exist try: cur_doc.save(1) out += "Created: " + cur_doc.name + "\n" created_docs.append(cur_doc) # make in groups if cur_doc.parent: if not doc_list.has_key(cur_doc.parent): doc_list[cur_doc.parent] = [] doc_list[cur_doc.parent].append(cur_doc) except Exception, e: out += "Creation Warning/Error: " + cur_doc.name + " :"+ str(e) + "\n" already_exists.append(cur_doc.name)
def add(): """add in someone's to do list""" if webnotes.conn.sql("""select owner from `tabToDo Item` where reference_type=%(doctype)s and reference_name=%(name)s and owner=%(assign_to)s""", webnotes.form_dict): webnotes.msgprint("Already in todo") return else: from webnotes.model.doc import Document from webnotes.utils import nowdate d = Document("ToDo Item") d.owner = webnotes.form_dict['assign_to'] d.reference_type = webnotes.form_dict['doctype'] d.reference_name = webnotes.form_dict['name'] d.description = webnotes.form_dict['description'] d.priority = webnotes.form_dict.get('priority', 'Medium') d.date = webnotes.form_dict.get('date', nowdate()) d.assigned_by = webnotes.user.name d.save(1) # notify notify_assignment(d.assigned_by, d.owner, d.reference_type, d.reference_name, action='ASSIGN', notify=webnotes.form_dict.get('notify')) # update feeed try: import home from webnotes.utils import get_fullname home.make_feed('Assignment', d.reference_type, d.reference_name, webnotes.session['user'], '[%s] Assigned to %s' % (d.priority, get_fullname(d.owner)), '#C78F58') except ImportError, e: pass
def close_session(session_id): from webnotes.model.doc import Document d = Document('Session',session_id) d.status = 'Close' d.save() return{ 'session_id':'' }
def naming_series(self): ns = [['TDS Payment', 'TDSP'], ['Payable Voucher', 'BILL'], ['Journal Voucher', 'JV'], ['Receivable Voucher', 'INV'], ['Lead', 'Lead'], ['Indent', 'IDT'], ['Enquiry', 'Enquiry'], ['Purchase Order', 'PO'], ['Quotation', 'QTN'], ['Purchase Receipt', 'GRN'], ['Stock Entry', 'STE'], ['Sales Order', 'SO'], ['Delivery Note', 'DN'], ['Employee', 'EMP/']] for r in ns: rec = Document('Naming Series') rec.select_doc_for_series = r[0] rec.new_series = r[1] rec_obj = get_obj(doc=rec) rec_obj.add_series()
def add_guest_access_to_page(page): """add Guest in Page Role""" if not webnotes.conn.sql("""select parent from `tabPage Role` where role='Guest' and parent=%s""", page): d = Document('Page Role') d.parent = page d.role = 'Guest' d.save()
def set_user_details(arg=None): "updates user details given in argument" from webnotes.model.doc import Document p = Document('Profile', webnotes.user.name) p.fields.update(load_json(arg)) p.save() webnotes.msgprint('Updated')
def execute(): companies_list = webnotes.conn.sql("SELECT company_name FROM `tabCompany`", as_list=1) for company in companies_list: if company and company[0]: edigest = Document('Email Digest', "Default Weekly Digest - " + company[0]) if edigest: edigest.income_year_to_date = 1 edigest.save()
def execute(): from webnotes.model.doc import Document from webnotes.modules import reload_doc reload_doc('hr', 'search_criteria', 'employeewise_balance_leave_report') d = Document('Search Criteria', 'employeewise_balance_leave_report') d.criteria_name = 'Employee Leave Balance Report' d.description = 'Employeewise Balance Leave Report' d.save()
def create_session(): from webnotes.model.doc import Document d = Document('Session') d.status = 'Open' d.test_name='Neutralization Value' d.save() return{ 'session_id':d.name }
def create_session(): from webnotes.model.doc import Document d = Document('Session') d.status = 'Open' d.test_name='Interfacial Tension' d.save() return{ 'session_id':d.name }
def execute(): import webnotes from webnotes.model.doc import Document if not webnotes.conn.sql("select name from `tabRole` where name = 'Report Manager'"): r = Document('Role') r.role_name = 'Report Manager' r.module = 'Core' r.save()
def add_acc(self,lst): ac = Document('Account') for d in self.fld_dict.keys(): ac.fields[d] = (d == 'parent_account' and lst[self.fld_dict[d]]) and lst[self.fld_dict[d]] +' - '+ self.doc.abbr or lst[self.fld_dict[d]] ac_obj = get_obj(doc=ac) ac_obj.doc.freeze_account='No' ac_obj.doc.master_type = '' ac_obj.validate() ac_obj.doc.save(1) ac_obj.on_update()
def generate_sample(self): samples = {} # for sample in sample_list: d = Document("Sample") d.sample_entry = self.doc.s_entry d.barcode = self.doc.bottles_barcodes d.save() samples[d.name] = self.doc.bottles_barcodes self.fill_child_entry(samples)
def add_website_manager(): """add website manager to system manager""" for i in webnotes.conn.sql("""select distinct parent from tabUserRole where role='System Manager'"""): if not webnotes.conn.sql("""select parent from tabUserRole where role='Website Manager' and parent=%s""", i[0]): d = Document('UserRole') d.parent = i[0] d.role = 'Website Manager' d.save(1)
def add_node(): from webnotes.model.doc import Document ctype = webnotes.form_dict.get('ctype') parent_field = 'parent_' + ctype.lower().replace(' ', '_') d = Document(ctype) d.fields[ctype.lower().replace(' ', '_') + '_name'] = webnotes.form_dict['name_field'] d.fields[parent_field] = webnotes.form_dict['parent'] d.is_group = webnotes.form_dict['is_group'] d.save()
def add_website_manager(): """add website manager to system manager""" for i in webnotes.conn.sql("""select distinct parent from tabUserRole where role='System Manager'"""): if not webnotes.conn.sql( """select parent from tabUserRole where role='Website Manager' and parent=%s""", i[0]): d = Document('UserRole') d.parent = i[0] d.role = 'Website Manager' d.save(1)
def create_email_digest(self): """ create a default weekly email digest * Weekly Digest * For all companies * Recipients: System Managers * Full content * Enabled by default """ import webnotes companies_list = webnotes.conn.sql("SELECT company_name FROM `tabCompany`", as_list=1) import webnotes.utils system_managers = webnotes.utils.get_system_managers_list() if not system_managers: return from webnotes.model.doc import Document for company in companies_list: if company and company[0]: edigest = Document('Email Digest') edigest.name = "Default Weekly Digest - " + company[0] edigest.company = company[0] edigest.frequency = 'Weekly' edigest.recipient_list = "\n".join(system_managers) for f in ['new_leads', 'new_enquiries', 'new_quotations', 'new_sales_orders', 'new_purchase_orders', 'new_transactions', 'payables', 'payments', 'expenses_booked', 'invoiced_amount', 'collections', 'income', 'bank_balance', 'stock_below_rl', 'income_year_to_date', 'enabled']: edigest.fields[f] = 1 exists = webnotes.conn.sql("""\ SELECT name FROM `tabEmail Digest` WHERE name = %s""", edigest.name) if (exists and exists[0]) and exists[0][0]: continue else: edigest.save(1)
def on_update(self): #res="select account_id from `tabFranchise` where region='"+self.doc.region+"'" #rs=webnotes.conn.sql(res) #webnotes.errprint(rs) #self.doc.account_id=rs[0][0] #webnotes.errprint(self.doc.account_id) #self.doc.save() s = webnotes.conn.sql( "select customer_name from `tabCustomer` where territory='" + cstr(self.doc.region) + "' and name='" + self.doc.name + "'") #webnotes.errprint(s) if not s: d = Document('Customer') d.customer_name = self.doc.sf_name d.territory = self.doc.region d.account_id = self.doc.account_id d.sf_name = self.doc.sf_name d.customer_type = 'Company' d.customer_group = 'Commercial'
def set_series_for(self, doctype, ol): options = self.scrub_options_list(ol) # validate names for i in options: self.validate_series_name(i) if self.doc.user_must_always_select: options = [''] + options default = '' else: default = options[0] # update in property setter from webnotes.model.doc import Document prop_dict = {'options': "\n".join(options), 'default': default} for prop in prop_dict: ps_exists = webnotes.conn.sql("""SELECT name FROM `tabProperty Setter` WHERE doc_type = %s AND field_name = 'naming_series' AND property = %s""", (doctype, prop)) if ps_exists: ps = Document('Property Setter', ps_exists[0][0]) ps.value = prop_dict[prop] ps.save() else: ps = Document('Property Setter', fielddata = { 'doctype_or_field': 'DocField', 'doc_type': doctype, 'field_name': 'naming_series', 'property': prop, 'value': prop_dict[prop], 'property_type': 'Select', 'select_doctype': doctype }) ps.save(1) self.doc.set_options = "\n".join(options) webnotes.clear_cache(doctype=doctype)
def install_print_format(args): """ Installs print format args is a dict consisting of following keys: * name * module * doctype * standard = "Yes"/"No" * file """ from webnotes.model.doc import Document d = Document('Print Format') d.name = args['name'] f = open(args['file']) d.html = f.read() f.close() d.module = args['module'] d.doc_type = args['doc_type'] d.standard = args['standard'] d.save(1) from webnotes.model.code import get_obj obj = get_obj('Print Format', args['name']) obj.on_update()
def dt_map(): import webnotes import webnotes.model.utils from webnotes.model.code import get_obj from webnotes.model.doc import Document form_dict = webnotes.form_dict dt_list = webnotes.model.utils.expand(form_dict.get('docs')) from_doctype = form_dict.get('from_doctype') to_doctype = form_dict.get('to_doctype') from_docname = form_dict.get('from_docname') from_to_list = form_dict.get('from_to_list') dm = get_obj('DocType Mapper', from_doctype +'-' + to_doctype) dl = dm.dt_map(from_doctype, to_doctype, from_docname, Document(fielddata = dt_list[0]), [], from_to_list) webnotes.response['docs'] = dl
def send_welcome_mail(email, args): """send welcome mail to user with password and login url""" pr = Document('Profile', email) from webnotes.utils.email_lib import sendmail_md args.update({ 'company': webnotes.conn.get_default('company'), 'password': args.get('password'), 'account_url': webnotes.conn.get_value('Website Settings', 'Website Settings', 'subdomain') or "" }) if not args.get('last_name'): args['last_name'] = '' sendmail_md(pr.email, subject="Welcome to ERPNext", msg=welcome_txt % args, from_defs=1)
def make_entry(self, args): sle = Document(doctype = 'Stock Ledger Entry') for k in args.keys(): # adds warehouse_type if k == 'warehouse': sle.fields['warehouse_type'] = get_value('Warehouse' , args[k], 'warehouse_type') sle.fields[k] = args[k] sle_obj = get_obj(doc=sle) # validate sle_obj.validate() sle.save(new = 1) return sle.name
def execute(): from webnotes.modules import reload_doc reload_doc('core', 'doctype', 'print_format') reload_doc('core', 'doctype', 'doclayer') reload_doc('core', 'doctype', 'doclayerfield') reload_doc('accounts', 'doctype', 'gl_entry') from webnotes.model.doc import Document d = Document('DocType Label') d.dt = "Customize Form" d.dt_label = "Customize Form View" d.save(1) from webnotes.session_cache import clear clear()
def post(arg=None): import webnotes """post message""" if arg: import json arg = json.loads(arg) else: arg = {} arg.update(webnotes.form_dict) from webnotes.model.doc import Document d = Document('Comment') d.parenttype = arg.get("parenttype") d.comment = arg['txt'] d.comment_docname = arg['contact'] d.comment_doctype = 'Message' d.save() import webnotes.utils if webnotes.utils.cint(arg.get('notify')): notify(arg)
def create_production_order(self, items): """Create production order. Called from Production Planning Tool""" pro_list = [] for item_so in items: pro_doc = Document('Production Order') pro_doc.production_item = item_so[0] pro_doc.sales_order = item_so[1] for key in items[item_so]: pro_doc.fields[key] = items[item_so][key] pro_doc.save(new = 1) get_obj("Production Order", pro_doc.name).validate_production_order_against_so() pro_list.append(pro_doc.name) return pro_list
def create_auto_indent(self, i, doc_type, doc_name, cur_qty): """ Create indent on reaching reorder level """ indent = Document('Purchase Request') indent.transaction_date = nowdate() indent.naming_series = 'IDT' indent.company = get_defaults()['company'] indent.fiscal_year = get_defaults()['fiscal_year'] indent.remark = "This is an auto generated Purchase Request. It was raised because the (actual + ordered + indented - reserved) quantity reaches re-order level when %s %s was created" % ( doc_type, doc_name) indent.save(1) indent_obj = get_obj('Purchase Request', indent.name, with_children=1) indent_details_child = addchild(indent_obj.doc, 'indent_details', 'Purchase Request Item', 0) indent_details_child.item_code = self.doc.item_code indent_details_child.uom = self.doc.stock_uom indent_details_child.warehouse = self.doc.warehouse indent_details_child.schedule_date = add_days( nowdate(), cint(i['lead_time_days'])) indent_details_child.item_name = i['item_name'] indent_details_child.description = i['description'] indent_details_child.item_group = i['item_group'] indent_details_child.qty = i['re_order_qty'] or ( flt(i['re_order_level']) - flt(cur_qty)) indent_details_child.brand = i['brand'] indent_details_child.save() indent_obj = get_obj('Purchase Request', indent.name, with_children=1) indent_obj.validate() set(indent_obj.doc, 'docstatus', 1) indent_obj.on_submit() msgprint( "Item: " + self.doc.item_code + " is to be re-ordered. Purchase Request %s raised. It was generated from %s %s" % (indent.name, doc_type, doc_name)) if (i['email_notify']): send_email_notification(doc_type, doc_name)
def add_comment(): import time args = webnotes.form_dict if args.get('comment'): from webnotes.model.doc import Document from webnotes.utils import nowdate cmt = Document('Comment Widget Record') for arg in [ 'comment', 'comment_by', 'comment_by_fullname', 'comment_doctype', 'comment_docname' ]: cmt.fields[arg] = args[arg] cmt.comment_date = nowdate() cmt.comment_time = time.strftime('%H:%M') cmt.save(1)
def post_comment(arg): arg = load_json(arg) from webnotes.model.doc import Document d = Document('Comment Widget Record') d.comment_doctype = 'My Company' d.comment_docname = arg['uid'] # to d.owner = webnotes.user.name d.comment = arg['comment'] d.save(1) if cint(arg.get('notify')): fn = webnotes.conn.sql( 'select first_name, last_name from tabProfile where name=%s', webnotes.user.name)[0] if fn[0] or f[1]: fn = cstr(fn[0]) + (fn[0] and ' ' or '') + cstr(fn[1]) else: fn = webnotes.user.name message = '''A new comment has been posted on your page by %s: <b>Comment:</b> %s To answer, please login to your erpnext account! <a href='https://signin.erpnext.com'>https://signin.erpnext.com</a> ''' % (fn, arg['comment']) from webnotes.model.code import get_obj note = get_obj('Notification Control') email_msg = note.prepare_message({ 'type': 'New Comment', 'message': message }) sender = webnotes.user.name != 'Administrator' and webnotes.user.name or '*****@*****.**' from webnotes.utils.email_lib import sendmail sendmail([arg['uid']], sender, email_msg, fn + ' has posted a new comment')
def get_bin(self, item_code, warehouse=None): warehouse = warehouse or self.doc.name bin = sql( "select name from tabBin where item_code = %s and \ warehouse = %s", (item_code, warehouse)) bin = bin and bin[0][0] or '' if not bin: bin = Document('Bin') bin.item_code = item_code bin.stock_uom = webnotes.conn.get_value('Item', item_code, 'stock_uom') bin.warehouse = warehouse bin.warehouse_type = webnotes.conn.get_value( "Warehouse", warehouse, "warehouse_type") bin_obj = get_obj(doc=bin) bin_obj.validate() bin.save(1) bin = bin.name else: bin_obj = get_obj('Bin', bin) return bin_obj
def load_from_db(self, dt, dn): """ Load doclist from dt """ from webnotes.model.doc import Document, getchildren doc = Document(dt, dn, prefix=prefix) # get all children types tablefields = webnotes.model.meta.get_table_fields(dt) # load chilren doclist = [ doc, ] for t in tablefields: doclist += getchildren(doc.name, t[0], t[1], dt, prefix=prefix) self.docs = docs
def create_new_file(self, arg): arg = eval(arg) f = Document('File') f.file_name = arg['file_name'] f.description = arg['desc'] f.type = arg['type'] f.file_group = arg['file_grp'] f_obj = get_obj(doc=f) f_obj.validate() f_obj.doc.save(1) msgprint('Created a New File') ret = {'name': f_obj.doc.name, 'label': f_obj.doc.file_name} return ret
def create_doctype_label(): """ Creates a DocType Label Record for Indent """ res = webnotes.conn.sql("""\ SELECT name FROM `tabDocType Label` WHERE name='Indent' """) if not (res and res[0] and res[0][0]): from webnotes.model.doc import Document doclabel = Document('DocType Label') doclabel.dt = 'Indent' doclabel.dt_label = 'Purchase Requisition' doclabel.save(1)
def __init__(self): """ settings_doc must contain use_ssl, host, username, password """ from webnotes.model.doc import Document # extract email settings self.email_settings = Document('Email Settings', 'Email Settings') if not self.email_settings.fields.get('sync_support_mails'): return s = Document('Support Email Settings') s.use_ssl = self.email_settings.support_use_ssl s.host = self.email_settings.support_host s.username = self.email_settings.support_username s.password = self.email_settings.support_password POP3Mailbox.__init__(self, s)
def setUp(self): from webnotes.model.doc import Document self.root = Document(fielddata={ 'doctype': 'nsmtest', 'name': 'T001', 'parent': None }) self.first_child = Document(fielddata={ 'doctype': 'nsmtest', 'name': 'C001', 'parent_node': 'T001' }) self.first_sibling = Document(fielddata={ 'doctype': 'nsmtest', 'name': 'C002', 'parent_node': 'T001' }) self.grand_child = Document(fielddata={ 'doctype': 'nsmtest', 'name': 'GC001', 'parent_node': 'C001' }) webnotes.conn.sql(""" create table `tabnsmtest` ( name varchar(120) not null primary key, creation datetime, modified datetime, modified_by varchar(40), owner varchar(40), docstatus int(1) default '0', parent varchar(120), parentfield varchar(120), parenttype varchar(120), idx int(8), parent_node varchar(180), old_parent varchar(180), lft int, rgt int) ENGINE=InnoDB""")
def send_message(): from webnotes.model.doc import Document args = webnotes.form_dict d = Document('Support Ticket') d.subject = webnotes.form_dict.get('subject', 'Website Query') d.description = webnotes.form_dict.get('message') d.raised_by = webnotes.form_dict.get('sender') if not d.description: webnotes.msgprint('Please write something', raise_exception=True) if not d.raised_by: webnotes.msgprint( 'Please give us your email id so that we can write back to you', raise_exception=True) d.save() webnotes.msgprint('Thank you!')
def setUp(self): webnotes.conn.sql("delete from `tabItem Group`") self.data = [["t1", None, 1, 20], ["c0", "t1", 2, 3], ["c1", "t1", 4, 11], ["gc1", "c1", 5, 6], ["gc2", "c1", 7, 8], ["gc3", "c1", 9, 10], ["c2", "t1", 12, 17], ["gc4", "c2", 13, 14], ["gc5", "c2", 15, 16], ["c3", "t1", 18, 19]] for d in self.data: self.__dict__[d[0]] = Bean([ Document( fielddata={ "doctype": "Item Group", "item_group_name": d[0], "parent_item_group": d[1], "__islocal": 1 }) ]) self.save_all() self.reload_all()
def load_page(self, page): """ Load page meta tags and content """ from webnotes.model.doc import Document if not page: return if '/' in page: page = page.split('/')[0] if page=='Form': return try: doc = Document('Page', page) except: return self.keywords = doc.keywords self.site_description = doc.site_description self.title = doc.title self.get_page_content()
def add_roles(self, pr): roles_list = [ 'Accounts Manager', 'Accounts User', 'Blogger', 'HR Manager', 'HR User', 'Maintenance User', 'Maintenance Manager', 'Material Manager', 'Material User', 'Material Master Manager', 'Production Manager', 'Production User', 'Projects User', 'Purchase Manager', 'Purchase User', 'Purchase Master Manager', 'Quality Manager', 'Sales Manager', 'Sales User', 'Sales Master Manager', 'Support Manager', 'Support Team', 'System Manager', 'Website Manager' ] for r in roles_list: d = addchild(pr, 'userroles', 'UserRole', 1) d.role = r d.save(1) # Add roles to Administrator profile pr = Document('Profile', 'Administrator') for r in roles_list: d = addchild(pr, 'userroles', 'UserRole', 1) d.role = r d.save(1)
def map_fields(self, t, from_dt, from_dn, to_doc, doclist): """ Creates from, to obj and maps flds as per mapper and with same name """ flds = self.get_mapper_fields(t) flds += self.get_fields_with_same_name(t, flds) if flds: from_docnames = self.get_docnames(t, from_dt, from_dn) for dn in from_docnames: # Creates object for 'From DocType', it can be parent or child from_doc_obj = Document(t['from_table'], dn[0]) # Add a row in target table in 'To DocType' and returns obj if t['to_table'] != self.doc.to_doctype: to_doc_obj = addchild(to_doc, t['to_field'], t['to_table'], doclist) else: to_doc_obj = to_doc self.set_value(flds, from_doc_obj, to_doc_obj)
def load_from_db(self, dt=None, dn=None, prefix='tab'): """ Load doclist from dt """ from webnotes.model.doc import Document, getchildren if not dt: dt = self.doc.doctype if not dn: dn = self.doc.name doc = Document(dt, dn, prefix=prefix) # get all children types tablefields = webnotes.model.meta.get_table_fields(dt) # load chilren doclist = webnotes.doclist([ doc, ]) for t in tablefields: doclist += getchildren(doc.name, t[0], t[1], dt, prefix=prefix) self.set_doclist(doclist)
def get_bin(self, item_code): bin = sql( "select name from tabBin where item_code = %s and \ warehouse = %s", (item_code, self.doc.name)) bin = bin and bin[0][0] or '' if not bin: if not self.doc.warehouse_type: msgprint( "[Warehouse Type is Mandatory] Please Enter warehouse type in Warehouse " + self.doc.name) raise Exception bin = Document('Bin') bin.item_code = item_code bin.stock_uom = get_value('Item', item_code, 'stock_uom') bin.warehouse = self.doc.name bin.warehouse_type = self.doc.warehouse_type bin_obj = get_obj(doc=bin) bin_obj.validate() bin.save(1) bin = bin.name else: bin_obj = get_obj('Bin', bin) return bin_obj
def update_roles(self): """update roles if set""" if self.temp.get('roles'): from webnotes.model.doc import Document # remove roles webnotes.conn.sql("""delete from tabUserRole where parent='%s' and role in ('%s')""" % (self.doc.name, "','".join(self.temp['roles']['unset_roles']))) if "System Manager" in self.temp['roles']['unset_roles']: self.check_one_system_manager() # add roles user_roles = webnotes.get_roles(self.doc.name) for role in self.temp['roles']['set_roles']: if not role in user_roles: d = Document('UserRole') d.role = role d.parenttype = 'Profile' d.parentfield = 'user_roles' d.parent = self.doc.name d.save()
def post(arg=None): import webnotes """post message""" if not arg: arg = {} arg.update(webnotes.local.form_dict) if isinstance(arg, basestring): import json arg = json.loads(arg) from webnotes.model.doc import Document d = Document('Comment') d.parenttype = arg.get("parenttype") d.comment = arg['txt'] d.comment_docname = arg['contact'] d.comment_doctype = 'Message' d.save() delete_notification_count_for("Messages") import webnotes.utils if webnotes.utils.cint(arg.get('notify')): notify(arg)