def x_render_page(path): log("-- on render_page(%s)" % path) try: filepath, ext = os.path.splitext(path) # we only care about pages if ext not in [".js", ".css"]: user = frappe.get_user() if user.name == "Guest": email = random_string(20) + "@guest.local" user = frappe.get_doc({ "doctype": "User", "email": email, "first_name": "Guest User", "enabled": 1, "new_password": random_string(10), "user_type": "Website User" }) user.flags.ignore_permissions = True user.insert() frappe.local.login_manager.login_as(user.name) frappe.set_user(user.name) log("USER: %s" % user.name) result = x_render_page.patched_method(path) except Exception as ex: log(traceback.format_exc()) raise ex #log(result[0:40] + "...") return result
def work(): frappe.set_user(frappe.db.get_global('demo_hr_user')) year, month = frappe.flags.current_date.strftime("%Y-%m").split("-") mark_attendance() make_leave_application() # process payroll if not frappe.db.get_value("Salary Slip", {"month": month, "fiscal_year": year}): process_payroll = frappe.get_doc("Process Payroll", "Process Payroll") process_payroll.company = frappe.flags.company process_payroll.month = month process_payroll.fiscal_year = year process_payroll.create_sal_slip() process_payroll.submit_salary_slip() r = process_payroll.make_journal_entry(frappe.get_value('Account', {'account_name': 'Salary'})) journal_entry = frappe.get_doc(r) journal_entry.cheque_no = random_string(10) journal_entry.cheque_date = frappe.flags.current_date journal_entry.posting_date = frappe.flags.current_date journal_entry.insert() journal_entry.submit() if frappe.db.get_global('demo_hr_user'): make_timesheet_records() #expense claim expense_claim = frappe.new_doc("Expense Claim") expense_claim.extend('expenses', get_expenses()) expense_claim.employee = get_random("Employee") expense_claim.company = frappe.flags.company expense_claim.posting_date = frappe.flags.current_date expense_claim.exp_approver = filter((lambda x: x[0] != 'Administrator'), get_expense_approver(None, '', None, 0, 20, None))[0][0] expense_claim.insert() rand = random.random() if rand < 0.4: expense_claim.approval_status = "Approved" update_sanctioned_amount(expense_claim) expense_claim.submit() if random.randint(0, 1): #make journal entry against expense claim je = frappe.get_doc(make_bank_entry(expense_claim.name)) je.posting_date = frappe.flags.current_date je.cheque_no = random_string(10) je.cheque_date = frappe.flags.current_date je.flags.ignore_permissions = 1 je.submit() elif rand < 0.2: expense_claim.approval_status = "Rejected" expense_claim.submit()
def run_accounts(current_date): if can_make("Sales Invoice"): from erpnext.selling.doctype.sales_order.sales_order import make_sales_invoice report = "Ordered Items to be Billed" for so in list(set([r[0] for r in query_report.run(report)["result"] if r[0]!="Total"]))[:how_many("Sales Invoice")]: si = frappe.get_doc(make_sales_invoice(so)) si.posting_date = current_date si.fiscal_year = cstr(current_date.year) for d in si.get("entries"): if not d.income_account: d.income_account = "Sales - {}".format(company_abbr) si.insert() si.submit() frappe.db.commit() if can_make("Purchase Invoice"): from erpnext.stock.doctype.purchase_receipt.purchase_receipt import make_purchase_invoice report = "Received Items to be Billed" for pr in list(set([r[0] for r in query_report.run(report)["result"] if r[0]!="Total"]))[:how_many("Purchase Invoice")]: pi = frappe.get_doc(make_purchase_invoice(pr)) pi.posting_date = current_date pi.fiscal_year = cstr(current_date.year) pi.bill_no = random_string(6) pi.insert() pi.submit() frappe.db.commit() if can_make("Payment Received"): from erpnext.accounts.doctype.journal_voucher.journal_voucher import get_payment_entry_from_sales_invoice report = "Accounts Receivable" for si in list(set([r[4] for r in query_report.run(report, {"report_date": current_date })["result"] if r[3]=="Sales Invoice"]))[:how_many("Payment Received")]: jv = frappe.get_doc(get_payment_entry_from_sales_invoice(si)) jv.posting_date = current_date jv.cheque_no = random_string(6) jv.cheque_date = current_date jv.fiscal_year = cstr(current_date.year) jv.insert() jv.submit() frappe.db.commit() if can_make("Payment Made"): from erpnext.accounts.doctype.journal_voucher.journal_voucher import get_payment_entry_from_purchase_invoice report = "Accounts Payable" for pi in list(set([r[4] for r in query_report.run(report, {"report_date": current_date })["result"] if r[3]=="Purchase Invoice"]))[:how_many("Payment Made")]: jv = frappe.get_doc(get_payment_entry_from_purchase_invoice(pi)) jv.posting_date = current_date jv.cheque_no = random_string(6) jv.cheque_date = current_date jv.fiscal_year = cstr(current_date.year) jv.insert() jv.submit() frappe.db.commit()
def send_welcome_mail(password,profile_id,args, send_sms=True, is_provider=False): from frappe.utils import random_string, get_url key = random_string(32) db_set(args,"reset_password_key", key) link = get_url("/verify_email?id="+profile_id+"&key=" + key) mob_code = get_mob_code() update_verification_details(args,password,key,mob_code,link,profile_id, is_provider) mail_response = send_login_mail(args,"Verify Your Account", "templates/emails/new_user.html", {"link": link,"password":password,"verify_sms":send_sms}) if send_sms: mob_already_v = frappe.db.get_value("Mobile Verification",{"mobile_no":args["mobile"],"mflag":1},"name") if not mob_already_v: from phr.templates.pages.profile import make_mobile_verification_entry if not frappe.db.get_value("Mobile Verification",{"mobile_no":args["mobile"]},"name"): make_mobile_verification_entry(args["mobile"],profile_id,mob_code) else: pass from phr.templates.pages.utils import get_sms_template sms = get_sms_template("registration",{ "mobile_code": mob_code }) rec_list = [] rec_list.append(args["mobile"]) from erpnext.setup.doctype.sms_settings.sms_settings import send_sms send_sms(rec_list,sms) elif mob_already_v: vd = frappe.get_doc("Verification Details",profile_id) vd.mflag = 1 vd.save(ignore_permissions=True) return mail_response
def create_user_login(self): from frappe.utils import random_string password = random_string(10) user = frappe.get_doc({ "doctype":"User", "email": self.email, "profile_id": self.provider_id, "first_name": self.first_name, "last_name":self.last_name, "middle_name":self.middle_name, "enabled": 1, "contact":self.mobile_number, "new_password": password, "user_type": "Website User", "access_type":"Provider", "created_via": "Desktop", "password_str":password }) user.ignore_permissions = True user.no_welcome_mail = True user.insert() args = {'person_firstname':self.first_name,'person_middlename':self.middle_name, 'person_lastname':self.last_name,'email':self.email, 'mobile': self.mobile_number, "barcode":str(get_barcode())} notify = notify_user({}, args, self.provider_id, send_sms=False, is_provider=True) if notify.get("returncode") == 501: raise Exception(notify.get('msg_display'))
def sign_up(email, full_name): user = frappe.db.get("User", {"email": email}) if user: if user.disabled: return _("Registered but disabled.") else: return _("Already Registered") else: if ( frappe.db.sql( """select count(*) from tabUser where HOUR(TIMEDIFF(CURRENT_TIMESTAMP, TIMESTAMP(modified)))=1""" )[0][0] > 200 ): frappe.msgprint("Login is closed for sometime, please check back again in an hour.") raise Exception, "Too Many New Users" from frappe.utils import random_string user = frappe.get_doc( { "doctype": "User", "email": email, "first_name": full_name, "enabled": 1, "new_password": random_string(10), "user_type": "Website User", } ) user.flags.ignore_permissions = True user.insert() return _("Registration Details Emailed.")
def replace_filename_with_cid(message): """ Replaces <img embed="assets/frappe/images/filename.jpg" ...> with <img src="cid:content_id" ...> and return the modified message and a list of inline_images with {filename, filecontent, content_id} """ inline_images = [] while True: matches = re.search('''embed=["'](.*?)["']''', message) if not matches: break groups = matches.groups() # found match img_path = groups[0] filename = img_path.rsplit('/')[-1] filecontent = get_filecontent_from_path(img_path) if not filecontent: message = re.sub('''embed=['"]{0}['"]'''.format(img_path), '', message) continue content_id = random_string(10) inline_images.append({ 'filename': filename, 'filecontent': filecontent, 'content_id': content_id }) message = re.sub('''embed=['"]{0}['"]'''.format(img_path), 'src="cid:{0}"'.format(content_id), message) return (message, inline_images)
def sign_up(email, full_name, redirect_to): user = frappe.db.get("User", {"email": email}) if user: if user.disabled: return _("Registered but disabled.") else: return _("Already Registered") else: if frappe.db.sql("""select count(*) from tabUser where HOUR(TIMEDIFF(CURRENT_TIMESTAMP, TIMESTAMP(modified)))=1""")[0][0] > 300: frappe.respond_as_web_page(_('Temperorily Disabled'), _('Too many users signed up recently, so the registration is disabled. Please try back in an hour'), http_status_code=429) from frappe.utils import random_string user = frappe.get_doc({ "doctype":"User", "email": email, "first_name": full_name, "enabled": 1, "new_password": random_string(10), "user_type": "Website User" }) user.flags.ignore_permissions = True user.insert() if redirect_to: frappe.cache().hset('redirect_after_login', user.name, redirect_to) if user.flags.email_sent: return _("Please check your email for verification") else: return _("Please ask your administrator to verify your sign-up")
def test_make_vehicle_log(self): license_plate=random_string(10).upper() employee_id=frappe.db.sql("""select name from `tabEmployee` order by modified desc limit 1""")[0][0] vehicle = frappe.get_doc({ "doctype": "Vehicle", "license_plate": cstr(license_plate), "make": "Maruti", "model": "PCM", "last_odometer":5000, "acquisition_date":frappe.utils.nowdate(), "location": "Mumbai", "chassis_no": "1234ABCD", "vehicle_value":frappe.utils.flt(500000) }) try: vehicle.insert() except frappe.DuplicateEntryError: pass vehicle_log = frappe.get_doc({ "doctype": "Vehicle Log", "license_plate": cstr(license_plate), "employee":employee_id, "date":frappe.utils.nowdate(), "odometer":5010, "fuel_qty":frappe.utils.flt(50), "price": frappe.utils.flt(500) }) vehicle_log.insert() vehicle_log.submit()
def create_profile_in_db(id,args,response,path=None): from frappe.utils import random_string password = random_string(10) user = frappe.get_doc({ "doctype":"User", "email": args["email"], "profile_id":id, "first_name": args["person_firstname"], "middle_name": args["person_middlename"], "last_name": args["person_lastname"], "enabled": 1, "user_image": args.get('user_image'), "contact":args["mobile"], "new_password": password, "user_type": "Website User", "access_type":"Patient", "barcode":path, "created_via":args["received_from"], "password_str":password }) user.ignore_permissions = True user.no_welcome_mail = True user.insert() notify = notify_user(response,args,id) return _("Registration Details Emailed.")
def ldap_connect(): import ldap from frappe_ldap.templates.pages.ldap_login import get_details from frappe_ldap.ldap.doctype.ldap_settings.ldap_settings import set_ldap_connection server_details = get_details() connect, user_dn, base_dn = set_ldap_connection(server_details) filters = server_details.get('ldap_uidmapping')+"=*" # filters = "uid=*" new_created = [] enabled_profiles = [] try: #if authentication successful, get the full user data connect.simple_bind_s(user_dn, server_details.get('pwd')) except : connect.unbind_s() #search for users result = connect.search_s(base_dn, 2,filters) for dn, r in result: if r.get('mail'): password = random_string(10) role = r.get('description') if r.get('description') else 'Default' check_profile(r.get('mail')[0], r.get('uid')[0], password, role, new_created) enabled_profiles.append(r.get('mail')[0]) disable_profiles(enabled_profiles) admin_notification(new_created)
def test_party_status(self): from erpnext.accounts.doctype.payment_entry.payment_entry import get_payment_entry from frappe.utils import random_string customer_name = 'test customer for status' if frappe.db.exists('Customer', customer_name): customer = frappe.get_doc('Customer', customer_name) customer.db_set('status', 'Active') else: customer = frappe.get_doc({ 'doctype': 'Customer', 'customer_name': customer_name, 'customer_group': 'Commercial', 'customer_type': 'Individual', 'territory': 'Rest of the World' }).insert() self.assertEquals(frappe.db.get_value('Customer', customer.name, 'status'), 'Active') invoice = create_sales_invoice(customer="test customer for status", debit_to="_Test Receivable - _TC", currency="USD", conversion_rate=50) self.assertEquals(frappe.db.get_value('Customer', customer.name, 'status'), 'Open') pe = get_payment_entry(invoice.doctype, invoice.name) pe.reference_no = random_string(10) pe.reference_date = invoice.posting_date pe.insert() pe.submit() self.assertEquals(frappe.db.get_value('Customer', customer.name, 'status'), 'Active')
def store_property_photos_in_propshikari(request_data, custom_id): property_url_dict = {"full_size":[], "thumbnails":[]} size = 400,400 if request_data: putil.validate_for_property_photo_fields(request_data) if not os.path.exists(frappe.get_site_path("public","files",custom_id)): os.makedirs(frappe.get_site_path("public","files",custom_id,"regular")) os.mkdir(frappe.get_site_path("public","files",custom_id,"thumbnail")) for property_photo in request_data: file_ext = property_photo.get("file_ext") try: base64_data = property_photo.get("file_data").encode("utf8") base64_data = base64_data.split(',')[1] imgdata = base64.b64decode(base64_data) old_file_name = "PSPI-" + cstr(time.time()) + random_string(5) + "." + file_ext with open(frappe.get_site_path("public","files",custom_id,"regular",old_file_name),"wb+") as fi_nm: fi_nm.write(imgdata) file_name = "files/" + custom_id + "/regular/" + old_file_name regular_image_url = frappe.request.host_url + file_name property_url_dict.get("full_size").append(regular_image_url) thumbnail_file_name = frappe.get_site_path("public","files",custom_id,"thumbnail",old_file_name) im = Image.open(frappe.get_site_path("public","files",custom_id,"regular",old_file_name)) im.thumbnail(size, Image.ANTIALIAS) im.save(thumbnail_file_name) thumbnail_file_url = "files/" + custom_id + "/thumbnail/" + old_file_name property_url_dict.get("thumbnails").append(frappe.request.host_url + thumbnail_file_url) except Exception,e: raise ImageUploadError("Image Upload Error")
def test_expense_claim_status(self): payable_account = get_payable_account("Wind Power LLC") expense_claim = frappe.get_doc({ "doctype": "Expense Claim", "employee": "_T-Employee-0001", "payable_account": payable_account, "approval_status": "Approved", "expenses": [{ "expense_type": "Travel", "default_account": "Travel Expenses - WP", "claim_amount": 300, "sanctioned_amount": 200 }] }) expense_claim.submit() je_dict = make_bank_entry(expense_claim.name) je = frappe.get_doc(je_dict) je.posting_date = nowdate() je.cheque_no = random_string(5) je.cheque_date = nowdate() je.submit() expense_claim = frappe.get_doc("Expense Claim", expense_claim.name) self.assertEqual(expense_claim.status, "Paid") je.cancel() expense_claim = frappe.get_doc("Expense Claim", expense_claim.name) self.assertEqual(expense_claim.status, "Unpaid")
def send_welcome_mail(self): from frappe.utils import random_string, get_url key = random_string(32) self.db_set("reset_password_key", key) link = get_url("/update-password?key=" + key) self.send_login_mail(_("Verify Your Account"), "templates/emails/new_user.html", {"link": link})
def zip_attachments(document): zip_count = 1 zip_size = 0 document = json.loads(document) document2 = frappe._dict(document) fname = get_file_name(document2.name + " (zip 1).zip", random_string(7)) import zipfile docZip = zipfile.ZipFile(fname,"w", zipfile.ZIP_DEFLATED) for file_url in frappe.db.sql("""select file_url, is_private from `tabFile` where attached_to_doctype = %(doctype)s and attached_to_name = %(docname)s""", {'doctype': document2.doctype, 'docname': document2.name}, as_dict=True ): frappe.msgprint("Adding " + file_url.file_url) if file_url.file_url.startswith("/private/files/"): path = get_files_path(*file_url.file_url.split("/private/files/", 1)[1].split("/"), is_private=1) elif file_url.file_url.startswith("/files/"): path = get_files_path(*file_url.file_url.split("/files/", 1)[1].split("/")) path = encode(path) if zip_size + os.path.getsize(path) > 10000000: zip_count = zip_count + 1 zip_size = 0 docZip.close() with open(encode(fname), 'r') as f: content = f.read() content = base64.b64encode(content) save_file(fname, content, document2.doctype, document2.name, "Home/Attachments", 1) fname = get_file_name(document2.name + " (zip " + str(zip_count) + ").zip", random_string(7)) docZip = zipfile.ZipFile(fname,"w", zipfile.ZIP_DEFLATED) docZip.write(path, os.path.basename(path)) zip_size = zip_size + docZip.getinfo(os.path.basename(path)).compress_size docZip.close() with open(encode(fname), 'r') as f: content = f.read() content = base64.b64encode(content) save_file(fname, content, document2.doctype, document2.name, "Home/Attachments", 1)
def test_default_condition(self): '''test default condition is set''' todo = frappe.get_doc(dict(doctype='ToDo', description='workflow ' + random_string(10))).insert() # default condition is set self.assertEqual(todo.workflow_state, 'Pending') return todo
def get_random_filename(extn=None, content_type=None): if extn: if not extn.startswith("."): extn = "." + extn elif content_type: extn = mimetypes.guess_extension(content_type) return random_string(7) + (extn or "")
def work(): frappe.set_user(frappe.db.get_global('demo_hr_user')) year, month = frappe.flags.current_date.strftime("%Y-%m").split("-") prev_month = str(cint(month)- 1).zfill(2) if month=="01": prev_month = "12" mark_attendance() make_leave_application() # process payroll if not frappe.db.get_value("Salary Slip", {"month": prev_month, "fiscal_year": year}): process_payroll = frappe.get_doc("Process Payroll", "Process Payroll") process_payroll.company = frappe.flags.company process_payroll.month = prev_month process_payroll.fiscal_year = year process_payroll.from_date = frappe.flags.current_date process_payroll.to_date = add_days(frappe.flags.current_date, random.randint(0, 30)) process_payroll.reference_number = "DemoRef23" process_payroll.reference_date = frappe.flags.current_date process_payroll.payment_account = frappe.get_value('Account', {'account_type': 'Cash', 'company': erpnext.get_default_company(),'is_group':0}, "name") process_payroll.submit_salary_slip() process_payroll.make_journal_entry() if frappe.db.get_global('demo_hr_user'): make_timesheet_records() #expense claim expense_claim = frappe.new_doc("Expense Claim") expense_claim.extend('expenses', get_expenses()) expense_claim.employee = get_random("Employee") expense_claim.company = frappe.flags.company expense_claim.posting_date = frappe.flags.current_date expense_claim.exp_approver = filter((lambda x: x[0] != 'Administrator'), get_expense_approver(None, '', None, 0, 20, None))[0][0] expense_claim.insert() rand = random.random() if rand < 0.4: expense_claim.approval_status = "Approved" update_sanctioned_amount(expense_claim) expense_claim.submit() if random.randint(0, 1): #make journal entry against expense claim je = frappe.get_doc(make_bank_entry(expense_claim.name)) je.posting_date = frappe.flags.current_date je.cheque_no = random_string(10) je.cheque_date = frappe.flags.current_date je.flags.ignore_permissions = 1 je.submit() elif rand < 0.2: expense_claim.approval_status = "Rejected" expense_claim.submit()
def reset_password(self, send_email=False): from frappe.utils import random_string, get_url key = random_string(32) self.db_set("reset_password_key", key) link = get_url("/update-password?key=" + key) if send_email: self.password_reset_mail(link) return link
def get_conf_params(db_name=None, db_password=None): if not db_name: db_name = raw_input("Database Name: ") if not db_name: raise Exception("Database Name Required") if not db_password: from frappe.utils import random_string db_password = random_string(16) return {"db_name": db_name, "db_password": db_password}
def work(): frappe.set_user(frappe.db.get_global('demo_accounts_user')) if random.random() <= 0.6: report = "Ordered Items to be Billed" for so in list(set([r[0] for r in query_report.run(report)["result"] if r[0]!="Total"]))[:random.randint(1, 5)]: try: si = frappe.get_doc(make_sales_invoice(so)) si.posting_date = frappe.flags.current_date for d in si.get("items"): if not d.income_account: d.income_account = "Sales - {}".format(frappe.db.get_value('Company', si.company, 'abbr')) si.insert() si.submit() frappe.db.commit() except frappe.ValidationError: pass if random.random() <= 0.6: report = "Received Items to be Billed" for pr in list(set([r[0] for r in query_report.run(report)["result"] if r[0]!="Total"]))[:random.randint(1, 5)]: try: pi = frappe.get_doc(make_purchase_invoice(pr)) pi.posting_date = frappe.flags.current_date pi.bill_no = random_string(6) pi.insert() pi.submit() frappe.db.commit() except frappe.ValidationError: pass if random.random() < 0.5: make_payment_entries("Sales Invoice", "Accounts Receivable") if random.random() < 0.5: make_payment_entries("Purchase Invoice", "Accounts Payable") if random.random() < 0.1: #make payment request against sales invoice sales_invoice_name = get_random("Sales Invoice", filters={"docstatus": 1}) if sales_invoice_name: si = frappe.get_doc("Sales Invoice", sales_invoice_name) if si.outstanding_amount > 0: payment_request = make_payment_request(dt="Sales Invoice", dn=si.name, recipient_id=si.contact_email, submit_doc=True, mute_email=True, use_dummy_message=True) payment_entry = frappe.get_doc(make_payment_entry(payment_request.name)) payment_entry.posting_date = frappe.flags.current_date payment_entry.submit() make_pos_invoice()
def notify_user(res_data,user_args,profile_id): """ res_data = profile response from Solr user_args = arguments that are sent to createProfile Service of Solr profile_id = new user's profile id """ from frappe.utils import random_string new_password=random_string(10) _update_password(user_args["email"], new_password) db_set(user_args,"password_str",new_password) send_welcome_mail(new_password,profile_id,user_args)
def send_welcome_mail(self): from frappe.utils import random_string, get_url key = random_string(32) self.db_set("reset_password_key", key) link = get_url("/update-password?key=" + key) from frappe.utils import get_url, cstr frappe.errprint(get_url()) if get_url()=='http://tailorpad.com': self.send_login_mail2("Verify Your Account",link) else: self.send_login_mail("Verify Your Account", "templates/emails/new_user.html", {"link": link})
def test_make_vehicle(self): vehicle = frappe.get_doc({ "doctype": "Vehicle", "license_plate": random_string(10).upper(), "make": "Maruti", "model": "PCM", "last_odometer":5000, "acquisition_date":frappe.utils.nowdate(), "location": "Mumbai", "chassis_no": "1234ABCD", "vehicle_value":frappe.utils.flt(500000) }) vehicle.insert()
def make_payment_entries(ref_doctype, report): outstanding_invoices = list(set([r[3] for r in query_report.run(report, {"report_date": frappe.flags.current_date })["result"] if r[2]==ref_doctype])) # make Payment Entry for inv in outstanding_invoices[:random.randint(1, 2)]: pe = get_payment_entry(ref_doctype, inv) pe.posting_date = frappe.flags.current_date pe.reference_no = random_string(6) pe.reference_date = frappe.flags.current_date pe.insert() pe.submit() frappe.db.commit() outstanding_invoices.remove(inv) # make payment via JV for inv in outstanding_invoices[:1]: jv = frappe.get_doc(get_payment_entry_against_invoice(ref_doctype, inv)) jv.posting_date = frappe.flags.current_date jv.cheque_no = random_string(6) jv.cheque_date = frappe.flags.current_date jv.insert() jv.submit() frappe.db.commit()
def test_process_payroll(self): month = "11" fiscal_year = "_Test Fiscal Year 2016" payment_account = frappe.get_all("Account")[0].name if not frappe.db.get_value("Salary Slip", {"fiscal_year": fiscal_year, "month": month}): process_payroll = frappe.get_doc("Process Payroll", "Process Payroll") process_payroll.company = erpnext.get_default_company() process_payroll.month = month process_payroll.fiscal_year = fiscal_year process_payroll.from_date = "2016-11-01" process_payroll.to_date = "2016-11-30" process_payroll.payment_account = payment_account process_payroll.create_sal_slip() process_payroll.submit_salary_slip() if process_payroll.get_sal_slip_list(ss_status = 1): r = process_payroll.make_journal_entry(reference_number=random_string(10),reference_date=nowdate())
def test_expense_claim_status(self): payable_account = get_payable_account("Wind Power LLC") expense_claim = make_expense_claim(payable_account, 300, 200, "Wind Power LLC", "Travel Expenses - WP") je_dict = make_bank_entry("Expense Claim", expense_claim.name) je = frappe.get_doc(je_dict) je.posting_date = nowdate() je.cheque_no = random_string(5) je.cheque_date = nowdate() je.submit() expense_claim = frappe.get_doc("Expense Claim", expense_claim.name) self.assertEqual(expense_claim.status, "Paid") je.cancel() expense_claim = frappe.get_doc("Expense Claim", expense_claim.name) self.assertEqual(expense_claim.status, "Unpaid")
def create_user(self, rfq_supplier, link): user = frappe.get_doc({ 'doctype': 'User', 'send_welcome_email': 0, 'email': rfq_supplier.email_id, 'first_name': rfq_supplier.supplier_name, 'user_type': 'Website User' }) # reset password key = random_string(32) update_password_link = get_url("/update-password?key=" + key) user.reset_password_key = key user.redirect_url = link user.save(ignore_permissions=True) return user, update_password_link
def run_hr(current_date): year, month = current_date.strftime("%Y-%m").split("-") # process payroll if not frappe.db.get_value("Salary Slip", {"month": month, "fiscal_year": year}): process_payroll = frappe.get_doc("Process Payroll", "Process Payroll") process_payroll.company = settings.company process_payroll.month = month process_payroll.fiscal_year = year process_payroll.create_sal_slip() process_payroll.submit_salary_slip() r = process_payroll.make_journal_entry("Salary - WP") journal_entry = frappe.get_doc(r) journal_entry.cheque_no = random_string(10) journal_entry.cheque_date = current_date journal_entry.insert() journal_entry.submit()
def work(): frappe.set_user(frappe.db.get_global('demo_accounts_user')) if random.random() < 0.5: from erpnext.selling.doctype.sales_order.sales_order import make_sales_invoice report = "Ordered Items to be Billed" for so in list( set([ r[0] for r in query_report.run(report)["result"] if r[0] != "Total" ]))[:random.randint(1, 5)]: si = frappe.get_doc(make_sales_invoice(so)) si.posting_date = frappe.flags.current_date for d in si.get("items"): if not d.income_account: d.income_account = "Sales - {}".format( frappe.db.get_value('Company', si.company, 'abbr')) si.insert() si.submit() frappe.db.commit() if random.random() < 0.5: from erpnext.stock.doctype.purchase_receipt.purchase_receipt import make_purchase_invoice report = "Received Items to be Billed" for pr in list( set([ r[0] for r in query_report.run(report)["result"] if r[0] != "Total" ]))[:random.randint(1, 5)]: pi = frappe.get_doc(make_purchase_invoice(pr)) pi.posting_date = frappe.flags.current_date pi.bill_no = random_string(6) pi.insert() pi.submit() frappe.db.commit() from erpnext.accounts.doctype.journal_entry.journal_entry import get_payment_entry_against_invoice if random.random() < 0.5: report = "Accounts Receivable" for si in list( set([ r[3] for r in query_report.run( report, {"report_date": frappe.flags.current_date}) ["result"] if r[2] == "Sales Invoice" ]))[:random.randint(1, 5)]: jv = frappe.get_doc( get_payment_entry_against_invoice("Sales Invoice", si)) jv.posting_date = frappe.flags.current_date jv.cheque_no = random_string(6) jv.cheque_date = frappe.flags.current_date jv.insert() jv.submit() frappe.db.commit() if random.random() < 0.5: report = "Accounts Payable" for pi in list( set([ r[3] for r in query_report.run( report, {"report_date": frappe.flags.current_date}) ["result"] if r[2] == "Purchase Invoice" ]))[:random.randint(1, 5)]: jv = frappe.get_doc( get_payment_entry_against_invoice("Purchase Invoice", pi)) jv.posting_date = frappe.flags.current_date jv.cheque_no = random_string(6) jv.cheque_date = frappe.flags.current_date jv.insert() jv.submit() frappe.db.commit()
def autoname(self): self.password = random_string(16)
def create_new_todo(): return frappe.get_doc(dict(doctype='ToDo', description='workflow ' + random_string(10))).insert()
def run_accounts(current_date): if can_make("Sales Invoice"): from erpnext.selling.doctype.sales_order.sales_order import make_sales_invoice report = "Ordered Items to be Billed" for so in list( set([ r[0] for r in query_report.run(report)["result"] if r[0] != "Total" ]))[:how_many("Sales Invoice")]: si = frappe.get_doc(make_sales_invoice(so)) si.posting_date = current_date for d in si.get("items"): if not d.income_account: d.income_account = "Sales - {}".format( settings.company_abbr) si.insert() si.submit() frappe.db.commit() if can_make("Purchase Invoice"): from erpnext.stock.doctype.purchase_receipt.purchase_receipt import make_purchase_invoice report = "Received Items to be Billed" for pr in list( set([ r[0] for r in query_report.run(report)["result"] if r[0] != "Total" ]))[:how_many("Purchase Invoice")]: pi = frappe.get_doc(make_purchase_invoice(pr)) pi.posting_date = current_date pi.bill_no = random_string(6) pi.insert() pi.submit() frappe.db.commit() from erpnext.accounts.doctype.journal_entry.journal_entry import get_payment_entry_against_invoice if can_make("Payment Received"): report = "Accounts Receivable" for si in list( set([ r[3] for r in query_report.run( report, {"report_date": current_date})["result"] if r[2] == "Sales Invoice" ]))[:how_many("Payment Received")]: jv = frappe.get_doc( get_payment_entry_against_invoice("Sales Invoice", si)) jv.posting_date = current_date jv.cheque_no = random_string(6) jv.cheque_date = current_date jv.insert() jv.submit() frappe.db.commit() if can_make("Payment Made"): report = "Accounts Payable" for pi in list( set([ r[3] for r in query_report.run( report, {"report_date": current_date})["result"] if r[2] == "Purchase Invoice" ]))[:how_many("Payment Made")]: jv = frappe.get_doc( get_payment_entry_against_invoice("Purchase Invoice", pi)) jv.posting_date = current_date jv.cheque_no = random_string(6) jv.cheque_date = current_date jv.insert() jv.submit() frappe.db.commit()
def work(): frappe.set_user(frappe.db.get_global('demo_hr_user')) year, month = frappe.flags.current_date.strftime("%Y-%m").split("-") mark_attendance() make_leave_application() # payroll entry if not frappe.db.sql( 'select name from `tabSalary Slip` where month(adddate(start_date, interval 1 month))=month(curdate())' ): # process payroll for previous month payroll_entry = frappe.new_doc("Payroll Entry") payroll_entry.company = frappe.flags.company payroll_entry.payroll_frequency = 'Monthly' # select a posting date from the previous month payroll_entry.posting_date = get_last_day( getdate(frappe.flags.current_date) - datetime.timedelta(days=10)) payroll_entry.payment_account = frappe.get_value( 'Account', { 'account_type': 'Cash', 'company': erpnext.get_default_company(), 'is_group': 0 }, "name") payroll_entry.set_start_end_dates() # based on frequency payroll_entry.salary_slip_based_on_timesheet = 0 payroll_entry.create_salary_slips() payroll_entry.submit_salary_slips() payroll_entry.make_accrual_jv_entry() # payroll_entry.make_journal_entry(reference_date=frappe.flags.current_date, # reference_number=random_string(10)) payroll_entry.salary_slip_based_on_timesheet = 1 payroll_entry.create_salary_slips() payroll_entry.submit_salary_slips() payroll_entry.make_accrual_jv_entry() # payroll_entry.make_journal_entry(reference_date=frappe.flags.current_date, # reference_number=random_string(10)) if frappe.db.get_global('demo_hr_user'): make_timesheet_records() #expense claim expense_claim = frappe.new_doc("Expense Claim") expense_claim.extend('expenses', get_expenses()) expense_claim.employee = get_random("Employee") expense_claim.company = frappe.flags.company expense_claim.payable_account = get_payable_account( expense_claim.company) expense_claim.posting_date = frappe.flags.current_date expense_claim.insert() rand = random.random() if rand < 0.4: update_sanctioned_amount(expense_claim) expense_claim.submit() if random.randint(0, 1): #make journal entry against expense claim je = frappe.get_doc( make_bank_entry("Expense Claim", expense_claim.name)) je.posting_date = frappe.flags.current_date je.cheque_no = random_string(10) je.cheque_date = frappe.flags.current_date je.flags.ignore_permissions = 1 je.submit()
def before_insert(self): from frappe.utils import random_string self.key = random_string(32)
def work(): frappe.set_user(frappe.db.get_global('demo_hr_user')) year, month = frappe.flags.current_date.strftime("%Y-%m").split("-") setup_department_approvers() mark_attendance() make_leave_application() # payroll entry if not frappe.db.sql( 'select name from `tabSalary Slip` where month(adddate(start_date, interval 1 month))=month(curdate())' ): # based on frequency payroll_entry = get_payroll_entry() payroll_entry.salary_slip_based_on_timesheet = 0 payroll_entry.save() payroll_entry.create_salary_slips() payroll_entry.submit_salary_slips() payroll_entry.make_accrual_jv_entry() payroll_entry.submit() # payroll_entry.make_journal_entry(reference_date=frappe.flags.current_date, # reference_number=random_string(10)) # based on timesheet payroll_entry = get_payroll_entry() payroll_entry.salary_slip_based_on_timesheet = 1 payroll_entry.save() payroll_entry.create_salary_slips() payroll_entry.submit_salary_slips() payroll_entry.make_accrual_jv_entry() payroll_entry.submit() # payroll_entry.make_journal_entry(reference_date=frappe.flags.current_date, # reference_number=random_string(10)) if frappe.db.get_global('demo_hr_user'): make_timesheet_records() #expense claim expense_claim = frappe.new_doc("Expense Claim") expense_claim.extend('expenses', get_expenses()) expense_claim.employee = get_random("Employee") expense_claim.company = frappe.flags.company expense_claim.payable_account = get_payable_account( expense_claim.company) expense_claim.posting_date = frappe.flags.current_date expense_claim.expense_approver = frappe.db.get_global('demo_hr_user') expense_claim.save() rand = random.random() if rand < 0.4: update_sanctioned_amount(expense_claim) expense_claim.approval_status = 'Approved' expense_claim.submit() if random.randint(0, 1): #make journal entry against expense claim je = frappe.get_doc( make_bank_entry("Expense Claim", expense_claim.name)) je.posting_date = frappe.flags.current_date je.cheque_no = random_string(10) je.cheque_date = frappe.flags.current_date je.flags.ignore_permissions = 1 je.submit()
def work(): frappe.set_user(frappe.db.get_global('demo_hr_user')) year, month = frappe.flags.current_date.strftime("%Y-%m").split("-") prev_month = str(cint(month) - 1).zfill(2) if month == "01": prev_month = "12" mark_attendance() make_leave_application() # process payroll if not frappe.db.get_value("Salary Slip", { "month": prev_month, "fiscal_year": year }): process_payroll = frappe.get_doc("Process Payroll", "Process Payroll") process_payroll.company = frappe.flags.company process_payroll.month = prev_month process_payroll.fiscal_year = year process_payroll.create_sal_slip() process_payroll.submit_salary_slip() r = process_payroll.make_journal_entry( frappe.get_value('Account', {'account_name': 'Salary'})) journal_entry = frappe.get_doc(r) journal_entry.cheque_no = random_string(10) journal_entry.cheque_date = frappe.flags.current_date journal_entry.posting_date = frappe.flags.current_date journal_entry.insert() journal_entry.submit() if frappe.db.get_global('demo_hr_user'): make_timesheet_records() #expense claim expense_claim = frappe.new_doc("Expense Claim") expense_claim.extend('expenses', get_expenses()) expense_claim.employee = get_random("Employee") expense_claim.company = frappe.flags.company expense_claim.posting_date = frappe.flags.current_date expense_claim.exp_approver = filter( (lambda x: x[0] != 'Administrator'), get_expense_approver(None, '', None, 0, 20, None))[0][0] expense_claim.insert() rand = random.random() if rand < 0.4: expense_claim.approval_status = "Approved" update_sanctioned_amount(expense_claim) expense_claim.submit() if random.randint(0, 1): #make journal entry against expense claim je = frappe.get_doc(make_bank_entry(expense_claim.name)) je.posting_date = frappe.flags.current_date je.cheque_no = random_string(10) je.cheque_date = frappe.flags.current_date je.flags.ignore_permissions = 1 je.submit() elif rand < 0.2: expense_claim.approval_status = "Rejected" expense_claim.submit()
def work(): frappe.set_user(frappe.db.get_global('demo_accounts_user')) if random.random() <= 0.6: report = "Ordered Items to be Billed" for so in list( set([ r[0] for r in query_report.run(report)["result"] if r[0] != "Total" ]))[:random.randint(1, 5)]: try: si = frappe.get_doc(make_sales_invoice(so)) si.posting_date = frappe.flags.current_date for d in si.get("items"): if not d.income_account: d.income_account = "Sales - {}".format( frappe.get_cached_value('Company', si.company, 'abbr')) si.insert() si.submit() frappe.db.commit() except frappe.ValidationError: pass if random.random() <= 0.6: report = "Received Items to be Billed" for pr in list( set([ r[0] for r in query_report.run(report)["result"] if r[0] != "Total" ]))[:random.randint(1, 5)]: try: pi = frappe.get_doc(make_purchase_invoice(pr)) pi.posting_date = frappe.flags.current_date pi.bill_no = random_string(6) pi.insert() pi.submit() frappe.db.commit() except frappe.ValidationError: pass if random.random() < 0.5: make_payment_entries("Sales Invoice", "Accounts Receivable") if random.random() < 0.5: make_payment_entries("Purchase Invoice", "Accounts Payable") if random.random() < 0.4: #make payment request against sales invoice sales_invoice_name = get_random("Sales Invoice", filters={"docstatus": 1}) if sales_invoice_name: si = frappe.get_doc("Sales Invoice", sales_invoice_name) if si.outstanding_amount > 0: payment_request = make_payment_request( dt="Sales Invoice", dn=si.name, recipient_id=si.contact_email, submit_doc=True, mute_email=True, use_dummy_message=True) payment_entry = frappe.get_doc( make_payment_entry(payment_request.name)) payment_entry.posting_date = frappe.flags.current_date payment_entry.submit() make_pos_invoice()
def test_db_keywords_as_fields(self): """Tests if DB keywords work as docfield names. If they're wrapped with grave accents.""" # Using random.choices, picked out a list of 40 keywords for testing all_keywords = { "mariadb": ["CHARACTER", "DELAYED", "LINES", "EXISTS", "YEAR_MONTH", "LOCALTIME", "BOTH", "MEDIUMINT", "LEFT", "BINARY", "DEFAULT", "KILL", "WRITE", "SQL_SMALL_RESULT", "CURRENT_TIME", "CROSS", "INHERITS", "SELECT", "TABLE", "ALTER", "CURRENT_TIMESTAMP", "XOR", "CASE", "ALL", "WHERE", "INT", "TO", "SOME", "DAY_MINUTE", "ERRORS", "OPTIMIZE", "REPLACE", "HIGH_PRIORITY", "VARBINARY", "HELP", "IS", "CHAR", "DESCRIBE", "KEY"], "postgres": ["WORK", "LANCOMPILER", "REAL", "HAVING", "REPEATABLE", "DATA", "USING", "BIT", "DEALLOCATE", "SERIALIZABLE", "CURSOR", "INHERITS", "ARRAY", "TRUE", "IGNORE", "PARAMETER_MODE", "ROW", "CHECKPOINT", "SHOW", "BY", "SIZE", "SCALE", "UNENCRYPTED", "WITH", "AND", "CONVERT", "FIRST", "SCOPE", "WRITE", "INTERVAL", "CHARACTER_SET_SCHEMA", "ADD", "SCROLL", "NULL", "WHEN", "TRANSACTION_ACTIVE", "INT", "FORTRAN", "STABLE"] } created_docs = [] # edit by rushabh: added [:1] # don't run every keyword! - if one works, they all do fields = all_keywords[frappe.conf.db_type][:1] test_doctype = "ToDo" def add_custom_field(field): create_custom_field(test_doctype, { "fieldname": field.lower(), "label": field.title(), "fieldtype": 'Data', }) # Create custom fields for test_doctype for field in fields: add_custom_field(field) # Create documents under that doctype and query them via ORM for _ in range(10): docfields = {key.lower(): random_string(10) for key in fields} doc = frappe.get_doc({"doctype": test_doctype, "description": random_string(20), **docfields}) doc.insert() created_docs.append(doc.name) random_field = choice(fields).lower() random_doc = choice(created_docs) random_value = random_string(20) # Testing read self.assertEqual(list(frappe.get_all("ToDo", fields=[random_field], limit=1)[0])[0], random_field) self.assertEqual(list(frappe.get_all("ToDo", fields=[f"`{random_field}` as total"], limit=1)[0])[0], "total") # Testing read for distinct and sql functions self.assertEqual(list( frappe.get_all("ToDo", fields=[f"`{random_field}` as total"], distinct=True, limit=1, )[0] )[0], "total") self.assertEqual(list( frappe.get_all("ToDo", fields=[f"`{random_field}`"], distinct=True, limit=1, )[0] )[0], random_field) self.assertEqual(list( frappe.get_all("ToDo", fields=[f"count(`{random_field}`)"], limit=1 )[0] )[0], "count" if frappe.conf.db_type == "postgres" else f"count(`{random_field}`)") # Testing update frappe.db.set_value(test_doctype, random_doc, random_field, random_value) self.assertEqual(frappe.db.get_value(test_doctype, random_doc, random_field), random_value) # Cleanup - delete records and remove custom fields for doc in created_docs: frappe.delete_doc(test_doctype, doc) clear_custom_fields(test_doctype)
def reset_password(self): from frappe.utils import random_string, get_url key = random_string(32) self.db_set("reset_password_key", key) self.password_reset_mail(get_url("/update-password?key=" + key))
def get_random_filename(content_type=None): extn = None if content_type: extn = mimetypes.guess_extension(content_type) return random_string(7) + (extn or "")
def autoname(self): access_token = random_string(16) self.access_token = access_token
def sign_up(email, full_name, dob, phone_number, address, guardian_name, redirect_to): if not is_signup_enabled(): frappe.throw(_('Sign Up is disabled'), title='Not Allowed') user = frappe.db.get("User", {"email": email}) if user: if user.disabled: return 0, _("Registered but disabled") else: return 0, _("Already Registered") else: if frappe.db.sql("""select count(*) from tabUser where HOUR(TIMEDIFF(CURRENT_TIMESTAMP, TIMESTAMP(modified)))=1""")[0][0] > 300: frappe.respond_as_web_page( _('Temperorily Disabled'), _('Too many users signed up recently, so the registration is disabled. Please try back in an hour' ), http_status_code=429) from frappe.utils import random_string import datetime date_format_dict = { "yyyy-mm-dd": "%Y-%m-%d", "dd-mm-yyyy": "%d-%m-%Y", "dd/mm/yyyy": "%d/%m/%Y", "dd.mm.yyyy": "%d.%m.%Y", "mm/dd/yyyy": "%m/%d/%Y", "mm-dd-yyyy": "%m-%d-%Y" } get_date_format_string = date_format_dict["mm-dd-yyyy"] get_system_date_format = frappe.db.get_value("System Settings", None, "date_format") if get_system_date_format in date_format_dict: get_date_format_string = date_format_dict[str( get_system_date_format)] else: frappe.db.set_value("System Settings", None, "date_format", "mm-dd-yyyy") frappe.db.commit() datetime_obj = datetime.datetime.strptime(dob, '%Y-%m-%d').strftime( str(get_date_format_string)) user = frappe.get_doc({ "doctype": "User", "email": email, "first_name": full_name, "birth_date": frappe.utils.getdate(datetime_obj), "phone": phone_number, "address": address, "guardian_name": guardian_name, "enabled": 1, "new_password": random_string(10), "user_type": "Website User" }) user.flags.ignore_permissions = True user.insert() customer = frappe.get_doc({ "doctype": "Customer", "customer_name": full_name, "customer_type": "Individual" }) customer.flags.ignore_permissions = True customer.insert() # set default signup role as per Portal Settings default_role = frappe.db.get_value("Portal Settings", None, "default_role") if default_role: user.add_roles(default_role) # frappe.throw("--- "+ str(redirect_to) + " ---Hello") if redirect_to: frappe.cache().hset('redirect_after_login', user.name, redirect_to) if user.flags.email_sent: return 1, _("Please check your email for verification") else: return 2, _("Please ask your administrator to verify your sign-up")
def get_awc_session(): # get session id from request sid = frappe.local.session.get("awc_sid", frappe.local.request.cookies.get("awc_sid")) if sid: awc_sid = "awc_session_{0}".format(sid) awc_session = None # lets make sure IPs match before applying this sid if sid != None: awc_session = frappe.cache().get_value(awc_sid) if awc_session: if awc_session.get("session_ip") != frappe.local.request_ip: # IP do not match... force build session from scratch log(" - AWC Session IP ADDRESS MISTMATCH {0} != {1} ... Resetting\n{2}" .format(awc_session.get("session_ip"), frappe.local.request_ip, pretty_json(awc_session))) sid = None awc_sid = None awc_session = None if awc_session is None: if not sid: sid = random_string(64) awc_sid = "awc_session_{0}".format(sid) awc_session = { "session_ip": frappe.local.request_ip, "cart": { "items": [], "totals": { "sub_total": 0, "grand_total": 0, "other": [] } } } frappe.cache().set_value(awc_sid, awc_session) else: # update old session structures if not awc_session.get("cart"): awc_session["cart"] = { "items": [], "totals": { "sub_total": 0, "grand_total": 0, "other": [] } } if not awc_session["cart"].get("totals"): awc_session["cart"]["totals"] = { "sub_total": 0, "grand_total": 0, "other": [] } if not awc_session["cart"]["totals"].get("other"): awc_session["cart"]["totals"]["other"] = [] frappe.local.session["awc_sid"] = sid frappe.local.cookie_manager.set_cookie("awc_sid", frappe.local.session["awc_sid"]) return awc_session
def make_route(self): if not self.route: return cstr(frappe.db.get_value('Item Group', self.item_group, 'route')) + '/' + self.scrub((self.item_name if self.item_name else self.item_code) + '-' + random_string(5))
def get_message_id(): '''Returns Message ID created from doctype and name''' return "<{unique}@{site}>".format( site=frappe.local.site, unique=email.utils.make_msgid( random_string(10)).split('@')[0].split('<')[1])