def image_writter(profile_id, event_id=None, visit_id=None): import os, base64 data = {"profile_id": profile_id, "event_id": event_id, "visit_id": visit_id} filelist = get_image_details(data) for file_obj in filelist: tags = file_obj.get('tag_id').split('-')[2] folder = tag_dict.get(tags[:2]) sub_folder = sub_tag_dict.get(tags[:2]).get(tags[2:]) path = os.path.join(os.getcwd(), get_site_path().replace('.',"").replace('/', ""), 'public', 'files', data.get('profile_id'), data.get("event_id"), folder, sub_folder, file_obj.get('visit_id')) wfile_name = file_obj.get('temp_file_id').split('.')[0] + '-watermark.' + file_obj.get('temp_file_id').split('.')[1] if not os.path.exists(os.path.join(path, wfile_name)): frappe.create_folder(path) img_path = os.path.join(path, wfile_name) frappe.errprint(["visit_id", data.get('visit_id')]) data = { "entityid": file_obj.get('visit_id'), "profile_id": data.get('profile_id'), "event_id": data.get("event_id") or "", "tag_id": file_obj.get('tag_id'), "file_id": [ file_obj.get('temp_file_id') ], "file_location": [ img_path ] } res = write_file(data)
def execute(filters=None): day=1 frappe.errprint("hii") if filters: day=filters.get('idle_days') columns = get_columns() data = [] dbname=frappe.db.sql("""select site_name from `tabSubAdmin Info` """,as_dict=1) lst=[] qry_srt='select name,last_login from(' for key in dbname: temp1 =key['site_name'] temp =key['site_name'] if temp.find('.')!= -1: temp=temp.split('.')[0][:16] else: temp=temp[:16] qry="SELECT name,last_login,'%s' as site_name FROM "%(temp1) if temp : qry+=temp+'.tabUser where name not in ("Guest","Administrator") and (hour(timediff(now(), last_login))/24 > %s || last_login is null )'%(cint(day)) lst.append(qry) fin_qry=' UNION '.join(lst) qry=qry_srt+fin_qry+" where doc_name='Administrator')foo ORDER BY creation DESC limit 5" act_details=frappe.db.sql(fin_qry,as_list=1,debug=1) data=act_details return columns, data
def getdoc(doctype, name, user=None): """ Loads a doclist for a given document. This method is called directly from the client. Requries "doctype", "name" as form variables. Will also call the "onload" method on the document. """ if not (doctype and name): raise Exception, 'doctype and name required!' if not name: name = doctype if not frappe.db.exists(doctype, name): return [] try: doc = frappe.get_doc(doctype, name) run_onload(doc) if not doc.has_permission("read"): raise frappe.PermissionError, ("read", doctype, name) # add file list get_docinfo(doc) except Exception: frappe.errprint(frappe.utils.get_traceback()) frappe.msgprint(_('Did not load')) raise if doc and not name.startswith('_'): frappe.get_user().update_recent(doctype, name) frappe.response.docs.append(doc)
def report_error(status_code): if status_code!=404 or frappe.conf.logging: frappe.errprint(frappe.utils.get_traceback()) response = build_response("json") response.status_code = status_code return response
def calculate_sales(self): ss_list = frappe.db.sql(""" select name,title,grand_total,transaction_date from `tabQuotation` where project = %s and docstatus < 2""", self.name,as_dict = 1) frappe.errprint(ss_list) totalsales = 0 joiningtext = """<table class="table table-bordered table-condensed"> <tr> <td>Document</td> <td>Title</td> <td>Date</td> <td>Grand Total</td> </tr>""" for i, d in enumerate(ss_list): joiningtext += """<tr> <td>""" + str(d["name"]) +"""</td> <td>""" + str(d["title"]) +"""</td> <td>""" + str(d["transaction_date"]) +"""</td> <td>""" + str(fmt_money(d["grand_total"], precision=2)) +"""</td> </tr>""" totalsales = totalsales + flt(d["grand_total"]) joiningtext += """<tr> <td>Project Total</td> <td></td> <td></td> <td>""" + str(fmt_money(totalsales, precision=2)) +"""</td> </tr>""" joiningtext += """</table><br>""" self.sales_orders = joiningtext
def get_individual_visit_count_for_badges(visit_id,profile_id, req_id=None): if req_id: req_id = frappe.get_doc('Shared Requests', req_id) event_dict = json.loads(req_id.event_dict) sub_event_count = json.loads(req_id.sub_event_count) else: request_type="POST" url=get_base_url()+'admin/getvisitfilecount' args={"profileId":profile_id} response=get_response(url,json.dumps(args),request_type) res=response.text event_list=[] event_dict={} sub_event_count={} if res: jsonobj=json.loads(res) if jsonobj["returncode"]==139: for visit in json.loads(jsonobj["list"]): frappe.errprint([visit['visit']['entityid'], visit_id]) if visit['visit']['entityid']==visit_id: event_wise_count_dict(visit['visitFileMapCount'], event_dict,sub_event_count) break return get_count_dict(event_dict, sub_event_count)
def run_async_task(self, site=None, user=None, cmd=None, form_dict=None, hijack_std=False): ret = {} frappe.init(site) frappe.connect() frappe.local.task_id = self.request.id if hijack_std: original_stdout, original_stderr = sys.stdout, sys.stderr sys.stdout, sys.stderr = get_std_streams(self.request.id) frappe.local.stdout, frappe.local.stderr = sys.stdout, sys.stderr try: set_task_status(self.request.id, "Running") frappe.db.commit() frappe.set_user(user) # sleep(60) frappe.local.form_dict = frappe._dict(form_dict) execute_cmd(cmd, from_async=True) ret = frappe.local.response except Exception, e: frappe.db.rollback() ret = frappe.local.response http_status_code = getattr(e, "http_status_code", 500) ret['status_code'] = http_status_code frappe.errprint(frappe.get_traceback()) frappe.utils.response.make_logs() set_task_status(self.request.id, "Error", response=ret) task_logger.error('Exception in running {}: {}'.format(cmd, ret['exc']))
def get_ftv_member(): val=frappe.db.sql("select defkey,defvalue from `tabDefaultValue` where defkey in ('Cells','Senior Cells','PCFs','Churches','Group Churches','Zones','Regions') and parent='%s' limit 1"%(frappe.session.user),as_list=1) frappe.errprint(val) if val: if val[0][0]=='Cells': key='cell' value=val[0][1] elif val[0][0]=='Senior Cells': key='senior_cell' value=val[0][1] elif val[0][0]=='PCFs': key='pcf' value=val[0][1] elif val[0][0]=='Churches': key='Church' value=val[0][1] elif val[0][0]=='Group Churches': key='church_group' value=val[0][1] elif val[0][0]=='Zones': key='zone' value=val[0][1] elif val[0][0]=='Regions': key='region' value=val[0][1] return{ "key" : key, "value" : value } else: return{ "key" : 1, "value" : 1 }
def get_ticket_details(self): # return frappe.get_doc('Support Ticket', self.name) response = requests.get("""%(url)s/api/resource/Support Ticket/SUP-00001"""%{'url':get_url()}) # frappe.errprint(["""%(url)s/api/resource/Support Ticket/%(name)s"""%{'url':get_url(), 'name':self.name}]) frappe.errprint(response.text) return eval(response.text).get('data')
def upload(): # # get record details # dt = frappe.form_dict.doctype # dn = frappe.form_dict.docname file_url = frappe.form_dict.file_url filename = frappe.form_dict.filename # frappe.errprint([file_url, filename]) if not filename and not file_url: frappe.msgprint(_("Please select a file or url"), raise_exception=True) # save if filename: filedata = save_uploaded() # elif file_url: # filedata = save_url(file_url, dt, dn) frappe.errprint(["testing image uploader", filedata]) return { "site_path" : os.path.join(os.getcwd(), get_site_path().replace('.',"").replace('/', ""), 'public', 'files'), "file_name": filedata['fname'], "success_meg": filedata['msg'] }
def validate_duplicate(doc,method): if doc.get("__islocal"): res=frappe.db.sql("select name from `tabGroup Churches` where church_group='%s' and church_group_code='%s' and zone='%s'"%(doc.church_group,doc.church_group_code,doc.zone)) if res: frappe.throw(_("Another Group Church '{0}' With Group Church Name '{1}' and Church Group Code '{2}' exist in Zone '{3}'..!").format(res[0][0],doc.church_group,doc.church_group_code,doc.zone)) notify_msg = """Dear User,\n\n Group Church is created with name '%s' for zone '%s'. \n\nRegards,\n\n Love World Synergy"""%(doc.church_group,doc.zone) notify = frappe.db.sql("""select value from `tabSingles` where doctype='Notification Settings' and field='on_creation_of_a_new_cell_pcf_church'""",as_list=1) if notify: if "Email" in notify[0][0]: if doc.contact_email_id: frappe.sendmail(recipients=doc.contact_email_id, content=notify_msg, subject='Group Church Creation Notification') if "SMS" in notify[0][0]: if doc.contact_phone_no: send_sms(doc.contact_phone_no, notify_msg) if "Push Notification" in notify[0][0]: data={} data['Message']=notify_msg gcm = GCM('AIzaSyBIc4LYCnUU9wFV_pBoFHHzLoGm_xHl-5k') res1=frappe.db.sql("select device_id from tabUser where name ='%s'" %(doc.contact_email_id),as_list=1) frappe.errprint(res1) if res1: res1 = gcm.json_request(registration_ids=res1, data=data,collapse_key='uptoyou', delay_while_idle=True, time_to_live=3600) ofc = frappe.new_doc("Offices") ofc.office_id = doc.name ofc.office_name = doc.church_group ofc.office_code = doc.church_group_code ofc.insert()
def savedocs(doc, action): """save / submit / update doclist""" try: doc = frappe.get_doc(json.loads(doc)) set_local_name(doc) # action doc.docstatus = {"Save":0, "Submit": 1, "Update": 1, "Cancel": 2}[action] if doc.docstatus==1: doc.submit() else: try: doc.save() except frappe.NameError as e: doctype, name, original_exception = e if isinstance(e, tuple) else (doc.doctype or "", doc.name or "", None) frappe.msgprint(frappe._("{0} {1} already exists").format(doctype, name)) raise # update recent documents run_onload(doc) frappe.get_user().update_recent(doc.doctype, doc.name) send_updated_docs(doc) except Exception: if not frappe.local.message_log: frappe.msgprint(frappe._('Did not save')) frappe.errprint(frappe.utils.get_traceback()) raise
def install_db(root_login="******", root_password=None, db_name=None, source_sql=None, admin_password = '******', verbose=True, force=0, site_config=None, reinstall=False): frappe.flags.in_install_db = True db_name=db_name[:16] if "." in db_name: dn=db_name.split('.') db_name=dn[0] frappe.errprint(db_name) make_conf(db_name, site_config=site_config) if reinstall: frappe.connect(db_name=db_name) dbman = DbManager(frappe.local.db) dbman.create_database(db_name) else: frappe.local.db = make_connection(root_login, root_password) frappe.local.session = frappe._dict({'user':'******'}) create_database_and_user(force, verbose) frappe.conf.admin_password = admin_password frappe.connect(db_name=db_name) import_db_from_sql(source_sql, verbose) create_auth_table() frappe.flags.in_install_db = False
def authenticate_credentials(): """ Process Authorization header in HTTP response according to basic HTTP authorization. Request is stored as Wekzeug local, frappe provides access to headers. """ received_credentials = frappe.get_request_header("Authorization") # seems like a dummy post request if not received_credentials: return False # invalid HTTP basic authorization header if not received_credentials.startswith("Basic"): return False splitted_credentials = received_credentials.split(" ", 1) if len(splitted_credentials) != 2: frappe.errprint("SendGrid webhook authentication failed with header: {}".format( received_credentials)) return False received_credentials = splitted_credentials[1] for credentials in get_webhook_credentials(): # matched => authenticated if received_credentials == base64.b64encode(credentials): return True # no match => failure return False
def add_webhook(doc, session): """Use Mandrill API to add the webhook""" r = session.post(get_api_url("/webhooks/add.json"), data=json.dumps({ "key": doc.password, "url": get_webhook_post_url(), "description": _("Frappé Mandrill Integration"), "events": [ # subscribe to these events # NOTE: 'deferral' event wasn't allowed at the time of making this "send", "hard_bounce", "soft_bounce", "open", "click", "spam", "unsub", "reject" ] })) if r.status_code != 200: # something went wrong frappe.msgprint(_("Could not activate Mandrill Integration")) frappe.errprint(r.text) return # store its value in Email Account mandrill_webhook_key = r.json()["auth_key"] doc.db_set("mandrill_webhook_key", mandrill_webhook_key)
def validate(self): self._prev = frappe._dict({ "contact_date": frappe.db.get_value("Lead", self.name, "contact_date") if \ (not cint(self.get("__islocal"))) else None, "contact_by": frappe.db.get_value("Lead", self.name, "contact_by") if \ (not cint(self.get("__islocal"))) else None, }) self.set_status() if self.source == 'Campaign' and not self.campaign_name and session['user'] != 'Guest': frappe.throw(_("Campaign Name is required")) if self.email_id: if not validate_email_add(self.email_id): frappe.throw(_('{0} is not a valid email id').format(self.email_id)) if self.email_id == self.lead_owner: # Lead Owner cannot be same as the Lead self.lead_owner = None from frappe.utils import get_url, cstr if self.get("__islocal") and get_url()=='http://tailorpad.com': frappe.errprint("creating site from lead") frappe.get_doc({ "doctype": "Site Master", "client_name": self.company_name, "site_name": self.company_name, "email_id__if_administrator": self.email_id, "country": self.country }).insert()
def upload(): if not frappe.has_permission("BRS Entries", "create"): raise frappe.PermissionError from frappe.utils.csvutils import read_csv_content_from_uploaded_file from frappe.modules import scrub rows = read_csv_content_from_uploaded_file() rows = filter(lambda x: x and any(x), rows) if not rows: msg = [_("Please select a csv file")] return {"messages": msg, "error": msg} #Columns located at 4th row columns = [scrub(f) for f in rows[2]] ret = [] error = False from frappe.utils.csvutils import check_record, import_doc for i, row in enumerate(rows[3:]): if not row: continue row_idx = i + 3 d = frappe._dict(zip(columns, row)) d["doctype"] = "BRS Entries" try: check_record(d) ret.append(import_doc(d, "BRS Entries", 1, row_idx, submit=True)) except Exception, e: error = True ret.append('Error for row (#%d) %s : %s' % (row_idx, len(row)>1 and row[1] or "", cstr(e))) frappe.errprint(frappe.get_traceback())
def GetCount(): frappe.errprint("in get count details") oauth = OAuth(client_key='c069f82639779dba424a19da7bb3946e', client_secret='2586f31b9c69084ac431def208f055d1', resource_owner_key='f296cbe24a82dec20dd8878a43e4e2fd', resource_owner_secret='aa9625f1580a21d2d6d3c51d063f2456') h = {'Content-Type': 'application/json', 'Accept': 'application/json'} r = requests.get(url='http://staging.digitales.com.au.tmp.anchor.net.au/api/rest/count', headers=h, auth=oauth) d = json.loads(r.content) return d
def safe_request_method(*args, **kwargs): try: return request_method(*args, **kwargs) except requests.ConnectionError: frappe.errprint("Failed to connect to SendGrid API") except Exception as e: frappe.errprint("SendGrid API Request Error: {}".format(e.message))
def create_feedback(): frappe.errprint("creating feed back") import requests import json pr2 = frappe.db.sql("""select site_name from `tabSubAdmin Info`""") for site_name in pr2: #frappe.errprint(site_name) db_name=cstr(site_name[0]).split('.')[0] db_name=db_name[:16] abx="select name from `"+cstr(db_name)+"`.`tabFeed Back` where flag='false'" pr3 = frappe.db.sql(abx) for sn in pr3: login_details = {'usr': '******', 'pwd': 'admin'} url = 'http://tailorpad.com/api/method/login' headers = {'content-type': 'application/x-www-form-urlencoded'} response = requests.post(url, data='data='+json.dumps(login_details), headers=headers) test = {} url="http://"+cstr(site_name[0])+"/api/resource/Feed Back/"+cstr(sn[0]) response = requests.get(url) support_ticket = eval(response.text).get('data') del support_ticket['name'] del support_ticket['creation'] del support_ticket['modified'] url = 'http://tailorpad.com/api/resource/Feed Back' headers = {'content-type': 'application/x-www-form-urlencoded'} response = requests.post(url, data='data='+json.dumps(support_ticket), headers=headers) url="http://"+cstr(site_name[0])+"/api/resource/Feed Back/"+cstr(sn[0]) support_ticket={} support_ticket['flag']='True' response = requests.put(url, data='data='+json.dumps(support_ticket), headers=headers)
def create_stock_assignment(purchase_receipt,d,sales_order,ordered_qty,assigned_qty): #frappe.errprint("in stock assignment") stock_assignment=frappe.db.sql("""select name from `tabStock Assignment Log` where sales_order='%s' and item_code='%s'""" %(sales_order,d.item_code)) #frappe.errprint(stock_assignment) if stock_assignment: ass_qty= frappe.db.sql(""" select assigned_qty from `tabStock Assignment Log` where name='%s'"""%stock_assignment[0][0]) frappe.errprint(ass_qty) qty=assigned_qty+ass_qty[0][0] frappe.db.sql("""update `tabStock Assignment Log` set purchase_receipt='%s', sales_order='%s',assigned_qty='%s' where name='%s'""" %(purchase_receipt,sales_order,qty,stock_assignment[0][0])) frappe.db.commit() else: sa = frappe.new_doc('Stock Assignment Log') sa.purchase_receipt=purchase_receipt sa.sales_order=sales_order sa.ordered_qty=ordered_qty sa.assign_qty=assigned_qty sa.item_code=d.item_code sa.save(ignore_permissions=True)
def update_wo(wo_details, fields, woname, style_details, args=None, type_of_wo=None): from frappe.utils import cstr wo = frappe.get_doc('Work Order', woname) style_details = eval(style_details) for d in wo.get('wo_style'): for style in style_details: if d.field_name == style: frappe.db.sql("""update `tabWO Style` set image_viewer ='%s', default_value = '%s', abbreviation = '%s' where parent = '%s' and field_name = '%s' """%( cstr(style_details[style].get('image')), cstr(style_details[style].get('value')), cstr(style_details[style].get('abbr')), woname, style ), debug=1) frappe.db.sql("commit") wo_details = eval(wo_details) for d in wo.get('measurement_item'): for style in wo_details['Measurement Item']: frappe.errprint(style) if d.parameter == style[0]: frappe.db.sql("""update `tabMeasurement Item` set value ='%s' where parent = '%s' and name = '%s' """%(style[2], woname, d.name), debug=1) frappe.db.commit() wo.save(1) frappe.msgprint("Updated.....")
def sync(doc, method=None): """Sync Webhook under SendGrid account.""" if not doc.service == "SendGrid": return if not (doc.api_key and doc.enable_outgoing and doc.smtp_server and doc.email_id and doc.password): frappe.msgprint("Imposible to setup SendGrid webhook (incorrect of settings)") return webhook_url = None if doc.sendgrid_webhook_credentials: webhook_url = get_webhook_post_url(doc.sendgrid_webhook_credentials) if webhook_exists(doc.api_key, webhook_url): frappe.msgprint("SendGrid events webhook already exists") return credentials = generate_credentials() webhook_url = get_webhook_post_url(credentials) if add_webhook(doc.api_key, webhook_url): # save webhook credentials in Email Account doc.sendgrid_webhook_credentials = credentials doc.db_set("sendgrid_webhook_credentials", credentials) frappe.db.commit() frappe.msgprint("SendGrid events webhook created successfuly") else: frappe.msgprint("Failed to create SendGrid events webhook") frappe.errprint("Failed to create SendGrid events webhook") # always clear key cache clear_cache()
def assignmember(memberid,ftv): frappe.db.sql("""update `tabFirst Timer` set ftv_owner='%s' where name='%s' """ % (memberid,ftv)) # recipients='*****@*****.**' member=frappe.db.sql("select member_name,email_id,phone_1 from `tabMember` where name='%s'"%(memberid)) member_ph = frappe.db.sql("select phone_1 from `tabMember` where name='%s'"%(memberid)) ftvdetails=frappe.db.sql("select ftv_name,email_id,task_description,due_date,phone_1 from `tabFirst Timer` where name='%s'"%(ftv)) ftv_ph = frappe.db.sql("select phone_1 from `tabMember` where name='%s'"%(ftv)) msg_member="""Hello %s,\n The First Timer '%s' name: '%s' Email ID: '%s' is assigned to you for follow up.\n Regards,\n Verve """%(member[0][0],ftv,ftvdetails[0][0],ftvdetails[0][1]) msg_ftv="""Hello %s,\n The Member '%s' name: '%s' Email ID: '%s' is assigned to you for follow up.\n Regards, \n Verve """%(ftvdetails[0][0],memberid,member[0][0],member[0][1]) desc="""Member '%s' is assigned to First Timer '%s' for followup."""%(memberid,ftv) task=frappe.get_doc({ "doctype": "Task", "subject": "Assign For followup", "expected_start_date":nowdate(), "expected_start_date":add_days(nowdate(),2), "status": "Open", "project": "", "description":desc }).insert(ignore_permissions=True) if frappe.db.exists("User", ftvdetails[0][1]): frappe.share.add("Task", task.name, ftvdetails[0][1], write=0) if frappe.db.exists("User", member[0][1]): frappe.share.add("Task", task.name, member[0][1], write=1) notify = frappe.db.sql("""select value from `tabSingles` where doctype='Notification Settings' and field='assign_for_followup'""",as_list=1) if "Email" in notify[0][0]: if member: frappe.sendmail(recipients=member[0][1], content=msg_member, subject='Assign For FollowUp Notification') if ftvdetails: frappe.sendmail(recipients=ftvdetails[0][1], content=msg_ftv, subject='Assign For FollowUp Notification') if "SMS" in notify[0][0]: if member_ph: send_sms(member_ph[0], msg_member) if ftv_ph: send_sms(ftv_ph[0], msg_ftv) if "Push Notification" in notify[0][0]: data={} data['Message']=msg_member gcm = GCM('AIzaSyBIc4LYCnUU9wFV_pBoFHHzLoGm_xHl-5k') res=frappe.db.sql("select device_id from tabUser where name ='%s'" %(member[0][1]),as_list=1) frappe.errprint(res) if res: res = gcm.json_request(registration_ids=res, data=data,collapse_key='uptoyou', delay_while_idle=True, time_to_live=3600) # receiver_list=[] # receiver_list.append(member[0][2]) # frappe.errprint(['rev[0]',receiver_list[0]]) # if receiver_list[0] : # frappe.errprint(receiver_list[0]) # send_sms(receiver_list, cstr(msg_member)) # frappe.sendmail(recipients=member[0][1], sender='*****@*****.**', content=msg_member, subject='Assign for follow up') # frappe.sendmail(recipients=ftvdetails[0][1], sender='*****@*****.**', content=msg_ftv, subject='Assign for follow up') return "Done"
def validate_user_company(self): if self.get("__islocal"): user = frappe.db.sql("""select u.name from tabUser u,tabUserRole r where r.parent=u.name and r.role='Admin' and u.company='%s'"""%(self.company),as_list=1) frappe.errprint(user) if user: frappe.throw(_("Admin '{0}' is already created for company '{1}',you cannot create two admin users for one company !").format(user[0][0],self.company))
def update_controller_context(context, controller): module = frappe.get_module(controller) if module: # get config fields for prop in ("base_template_path", "template", "no_cache", "no_sitemap", "condition_field"): if hasattr(module, prop): context[prop] = getattr(module, prop) if hasattr(module, "get_context"): try: ret = module.get_context(context) if ret: context.update(ret) except frappe.Redirect: raise except (frappe.PermissionError, frappe.DoesNotExistError): raise except: if not frappe.flags.in_migrate: frappe.errprint(frappe.utils.get_traceback()) if hasattr(module, "get_children"): context.children = module.get_children(context)
def validate_duplicate(doc,method): if doc.get("__islocal"): res=frappe.db.sql("select name from `tabZones` where (zone_name='%s' or zone_code='%s') and region='%s'"%(doc.zone_name,doc.zone_code,doc.region)) frappe.errprint(res) if res: frappe.throw(_("Zone '{0}' already created with same Zone Name '{1}' or Zone Code '{2}' for Region '{3}'..!").format(res[0][0],doc.zone_name,doc.zone_code,doc.region)) notify_msg = """Dear User,\n Region is created with name '%s' for region '%s' \n \n Regards,\n Love World Synergy"""%(doc.zone_name,doc.region) notify = frappe.db.sql("""select value from `tabSingles` where doctype='Notification Settings' and field='on_creation_of_a_new_cell_pcf_church'""",as_list=1) if "Email" in notify[0][0]: if doc.contact_email_id: frappe.sendmail(recipients=doc.contact_email_id, content=notify_msg, subject='Region Creation Notification') if "SMS" in notify[0][0]: if doc.contact_phone_no: send_sms(doc.contact_phone_no, notify_msg) if "Push Notification" in notify[0][0]: data={} data['Message']=notify_msg gcm = GCM('AIzaSyBIc4LYCnUU9wFV_pBoFHHzLoGm_xHl-5k') res1=frappe.db.sql("select device_id from tabUser where name ='%s'" %(doc.contact_email_id),as_list=1) frappe.errprint(res1) if res1: res1 = gcm.json_request(registration_ids=res1, data=data,collapse_key='uptoyou', delay_while_idle=True, time_to_live=3600)
def cancle_jv(si): for jv in frappe.db.sql("""select name from `tabJournal Voucher` where user_remark like '%%%s%%' and docstatus = 1"""%(si.name),as_list=1): frappe.errprint(jv) c_jc = frappe.get_doc("Journal Voucher", jv[0]) c_jc.cancel()
def validate_duplicate(doc,method): frappe.errprint("hello gangadhar") frappe.errprint(doc.data_17) if doc.get("__islocal"): if not doc.invitation_member_details: doc.load_participents() fdate=doc.from_date.split(" ") f_date=fdate[0] tdate=doc.to_date.split(" ") t_date=tdate[0] res=frappe.db.sql("select name from `tabAttendance Record` where (cell='%s' or church='%s') and from_date like '%s%%' and to_date like '%s%%'"%(doc.cell,doc.church,f_date,t_date)) #frappe.errprint(res) if res: frappe.throw(_("Attendance Record '{0}' is already created for same details on same date '{1}'").format(res[0][0],f_date)) if doc.from_date and doc.to_date: if doc.from_date >= doc.to_date: frappe.throw(_("To Date should be greater than From Date..!")) if len(doc.invitation_member_details)<1: pass #rappe.throw(_("Attendance Member table is empty.There should be at least 1 member in attendance list. Please load members in table.")) if doc.data_17 and cint(doc.data_17) <= 0 : frappe.throw(_("Total Attendance cannot be negative..!")) if doc.number_of_first_timers and cint(doc.number_of_first_timers) <= 0 : frappe.throw(_("Number of First Timers cannot be negative..!")) if doc.data_19 and cint(doc.data_19) <= 0 : frappe.throw(_("Number of New Converts cannot be negative..!")) if doc.data_20 and cint(doc.data_20) <= 0 : frappe.throw(_("Total Cell Offering cannot be negative..!"))
def report_error(status_code): if (status_code!=404 or frappe.conf.logging) and not frappe.local.flags.disable_traceback: frappe.errprint(frappe.utils.get_traceback()) response = build_response("json") response.status_code = status_code return response
def create_update_event(data=None, req_id=None): # url="http://88.198.52.49:7974/phr/createEvent" data = json.loads(data) frappe.errprint(['req_id', req_id]) if not data.get('entityid'): return create_event(data) else: res = update_event(data) if res.get('returncode') == 116: clear_dms_list(data.get('dms_file_list')) copy_files_to_visit(data.get('dms_file_list'), res.get('visit').get('entityid'), data.get('profile_id'), data.get('pid'), req_id) res['entityid'] = res['event']['entityid'] return res
def submit(doctype=None, name=None): """submit a doclist""" try: if not '[' in name: name = '["{}"]'.format(name) name_list = json.loads(name) for name_instance in name_list: doc = frappe.get_doc(doctype, name_instance) doc.submit() return 'ok' except Exception: frappe.errprint(frappe.utils.get_traceback()) frappe.msgprint(frappe._("Did not Submit")) raise
def create_bom(item, item_details, company, currency, qty, sales_order): try: bom_doc = frappe.get_doc( dict(doctype="BOM", company=company, currency=currency, item=item, items=item_details, quantity=qty, rm_cost_as_per="Valuation Rate", sales_order=sales_order)).insert() msg = 'BOM ' + '<a href="#Form/BOM/' + bom_doc.name + '">' + bom_doc.name + '</a>' + ' Created' frappe.msgprint(msg) except Exception as e: frappe.errprint(json.dumps(item_details)) error_log = app_error_log(frappe.session.user, str(e))
def validate_duplicate(doc, method): if doc.get("__islocal"): res = frappe.db.sql( "select name from `tabChurches` where church_name='%s' and church_group='%s' and church_code='%s'" % (doc.church_name, doc.church_group, doc.church_code)) if res: frappe.throw( _("Another Church '{3}' With Church Name '{0}' and Church Code '{2}'' exist in Church Group '{1}'" ).format(doc.church_name, doc.church_group, doc.church_code, res[0][0])) notify_msg = """Dear User,\n\n Church is created with name '%s' for Group Church '%s'. \n\n Regards,\n\n Love World Synergy""" % ( doc.church_name, doc.church_group) notify = frappe.db.sql( """select value from `tabSingles` where doctype='Notification Settings' and field='on_creation_of_a_new_cell_pcf_church'""", as_list=1) if notify: if "Email" in notify[0][0]: if doc.email_id: frappe.sendmail(recipients=doc.email_id, content=notify_msg, subject='Church Creation Notification') if "SMS" in notify[0][0]: if doc.phone_no: send_sms(doc.phone_no, notify_msg) if "Push Notification" in notify[0][0]: data = {} data['Message'] = notify_msg gcm = GCM('AIzaSyBIc4LYCnUU9wFV_pBoFHHzLoGm_xHl-5k') res1 = frappe.db.sql( "select device_id from tabUser where name ='%s'" % (doc.email_id), as_list=1) frappe.errprint(res1) if res1: res1 = gcm.json_request(registration_ids=res1, data=data, collapse_key='uptoyou', delay_while_idle=True, time_to_live=3600) ofc = frappe.new_doc("Offices") ofc.office_id = doc.name ofc.office_name = doc.church_name ofc.office_code = doc.church_code ofc.insert()
def delete_items(): """delete selected items""" import json from frappe.model.code import get_obj il = json.loads(frappe.form_dict.get('items')) doctype = frappe.form_dict.get('doctype') for d in il: try: dt_obj = get_obj(doctype, d) if hasattr(dt_obj, 'on_trash'): dt_obj.on_trash() frappe.delete_doc(doctype, d) except Exception, e: frappe.errprint(frappe.get_traceback()) pass
def get_hash_code(template_name, attribute_value_list): if isinstance(template_name, basestring): att_str = template_name else: att_str = template_name.name #att_str = template_name attributes = get_item_variant_attributes_values(template_name) frappe.errprint("attributes: " + cstr(attributes)) frappe.errprint("attribute_value_list: " + cstr(attribute_value_list)) for value in attribute_value_list: att_str += value bytes = att_str.encode("UTF-8") hash_object = hashlib.md5(bytes) return hash_object.hexdigest()
def upload(): if not frappe.has_permission("Attendance", "create"): raise frappe.PermissionError from frappe.utils.csvutils import read_csv_content_from_uploaded_file from frappe.modules import scrub rows = read_csv_content_from_uploaded_file() rows = list(filter(lambda x: x and any(x), rows)) if not rows: msg = [_("Please select a csv file")] return {"messages": msg, "error": msg} columns = [scrub(f) for f in rows[4]] columns[0] = "name" columns[3] = "attendance_date" ret = [] error = False from frappe.utils.csvutils import check_record, import_doc for i, row in enumerate(rows[5:]): if not row: continue row_idx = i + 5 d = frappe._dict(zip(columns, row)) d["doctype"] = "Attendance" if d.name: d["docstatus"] = frappe.db.get_value("Attendance", d.name, "docstatus") try: check_record(d) ret.append(import_doc(d, "Attendance", 1, row_idx, submit=True)) except AttributeError: pass except Exception as e: error = True ret.append('Error for row (#%d) %s : %s' % (row_idx, len(row) > 1 and row[1] or "", cstr(e))) frappe.errprint(frappe.get_traceback()) if error: frappe.db.rollback() else: frappe.db.commit() return {"messages": ret, "error": error}
def get_candidate_list(allkeywords, currentlocation, experience, prefferedlocation, annualincome, notinexcluding, functionarea, expectedsalary, industry, noticeperiod, ug, pg, ugspecialization, pgspecialization, institutename, yearofpassedout): condition = "" if allkeywords: condition += " functionaldesignationskills_area='%s'" % allkeywords if currentlocation: condition += "and current_location='%s'" % currentlocation if experience: condition += "and experiance='%s'" % experience if prefferedlocation: condition += "and preffered_location='%s'" % prefferedlocation if annualincome: condition += "and annual_income='%s'" % annualincome if notinexcluding: condition += "and not notin_excluding='%s'" % notinexcluding if functionarea: condition += "and functionaldesignationskills_area='%s'" % functionarea if expectedsalary: condition += "and expected_salary='%s'" % expectedsalary if industry: condition += "and industry='%s'" % industry if noticeperiod: condition += "and notice_period_1='%s'" % noticeperiod if ug: condition += "and course='%s'" % ug if pg: condition += "and pg='%s'" % pg if ugspecialization: condition += "and specialization='%s'" % ugspecialization if pgspecialization: condition += "and pg_specialization='%s'" % pgspecialization if institutename: condition += "and institute_name='%s'" % institutename if yearofpassedout: condition += "and passing_out_year='%s'" % yearofpassedout frappe.errprint(condition) candidate_list = frappe.db.sql( """select first_name,mobile,email_id,current_location from `tabCandidate Detail` where %s""" % condition, as_dict=1) return (candidate_list)
def get_events_grid(start, end,filters=None): import json filters=json.loads(filters) events = frappe.db.sql("""select name, employee, employee as resource ,starts_on, ends_on, customer, status,0 as all_day from `tabAppointment` where (( (date(starts_on) between date('%(start)s') and date('%(end)s')) or (date(ends_on) between date('%(start)s') and date('%(end)s')) or (date(starts_on) <= date('%(start)s') and date(ends_on) >= date('%(end)s')) )) order by starts_on""" % { "start": start, "end": end }, as_dict=1) frappe.errprint(events) employees=frappe.db.sql("""select name as id,employee_name as name from tabEmployee where status='Active' order by name """, as_dict=1) # frappe.errprint(employees) return events,employees
def log_query(self, query, values, debug, explain): # for debugging in tests if frappe.conf.get("allow_tests") and frappe.cache().get_value( "flag_print_sql"): print(self.mogrify(query, values)) # debug if debug: if explain and query.strip().lower().startswith("select"): self.explain_query(query, values) frappe.errprint(self.mogrify(query, values)) # info if (frappe.conf.get("logging") or False) == 2: frappe.log("<<<< query") frappe.log(self.mogrify(query, values)) frappe.log(">>>>")
def get_result_as_list(data, filters): balance, balance_in_account_currency = 0, 0 inv_details = get_supplier_invoice_details() for d in data: if not d.get('posting_date'): balance, balance_in_account_currency = 0, 0 balance = get_balance(d, balance, 'debit', 'credit') d['balance'] = balance d['account_currency'] = filters.account_currency d['bill_no'] = inv_details.get(d.get('against_voucher'), '') d['created_by'] = frappe.db.get_value(d.get('voucher_type'), d.get('voucher_no'), "owner") frappe.errprint(data) return data
def import_attendances(rows): from frappe.modules import scrub rows = list(filter(lambda x: x and any(x), rows)) columns = [scrub(f) for f in rows[4]] columns[0] = "name" columns[3] = "attendance_date" rows = rows[5:] ret = [] error = False from frappe.utils.csvutils import check_record, import_doc for i, row in enumerate(rows): if not row: continue row_idx = i + 5 d = frappe._dict(zip(columns, row)) d["doctype"] = "Attendance" if d.name: d["docstatus"] = frappe.db.get_value("Attendance", d.name, "docstatus") try: check_record(d) ret.append(import_doc(d, "Attendance", 1, row_idx, submit=True)) frappe.publish_realtime('import_attendance', dict( progress=i, total=len(rows) )) except AttributeError: pass except Exception as e: error = True ret.append('Error for row (#%d) %s : %s' % (row_idx, len(row)>1 and row[1] or "", cstr(e))) frappe.errprint(frappe.get_traceback()) if error: frappe.db.rollback() else: frappe.db.commit() frappe.publish_realtime('import_attendance', dict( messages=ret, error=error ))
def get_invoice_details(self, invoice_no=None): frappe.errprint("in the get_invoice fabric_details ") self.set('fabric_details', []) sales_invoices = frappe.db.sql("""select parent,tailoring_item_code,tailoring_item_name,tailoring_qty,fabric_code,fabric_qty,cut_fabric_status from `tabSales Invoice Items` where fabric_owner='Self' and cut_fabric_status='Pending'""",as_dict=1) frappe.errprint(sales_invoices) if sales_invoices: for inv in sales_invoices: si = self.append('fabric_details', {}) si.sales_invoice = inv.parent si.tailoring_item_code = inv.tailoring_item_code si.tailoring_item_name = inv.tailoring_item_name si.fabric_code = inv.fabric_code si.fabric_qty = inv.fabric_qty si.quantity=inv.tailoring_qty si.cut_fabric_status=inv.cut_fabric_status return "Done"
def uploadfile(): try: if frappe.form_dict.get('from_form'): try: ret = frappe.utils.file_manager.upload() except frappe.DuplicateEntryError: # ignore pass ret = None frappe.db.rollback() else: if frappe.form_dict.get('method'): ret = frappe.get_attr(frappe.form_dict.method)() except Exception: frappe.errprint(frappe.utils.get_traceback()) ret = None return ret
def get_filtered_date_list(employee,start_date,end_date,holiday_list): attendance = frappe.db.sql(""" SELECT count(name) as 'att_count' FROM `tabAttendance` WHERE attendance_date NOT IN (SELECT hd.holiday_date FROM `tabHoliday List` AS hl INNER JOIN `tabHoliday` AS hd ON hl.name=hd.parent WHERE hl.name=%s) AND employee=%s AND status='Present' AND docstatus=1 AND attendance_date BETWEEN %s AND %s """,(holiday_list,employee,start_date,end_date),as_dict=True) frappe.errprint(attendance) if attendance: return attendance[0].att_count else: return 0
def from_pos_call(doc, customer, item, qty): frappe.errprint([customer, item]) cwp = frappe.db.sql("select * from `tabCustomer wise package", as_list=1) check = [x[0] for x in cwp] # frappe.errprint(check) for c in check: cp = frappe.get_doc("Customer wise package", c) aaj = date.today().strftime('%Y-%m-%d') end_date = date.strftime(cp.valid_to, '%Y-%m-%d') if customer == cp.customer and item == cp.services and cp.quantity_issued >= int( int(cp.used_qty) + int(qty)) and aaj < end_date: # frappe.msgprint("call me") # cp.used_qty =cp.used_qty +1 # cp.save() return cp.package
def take_backup_to_dropbox(): did_not_upload, error_log = [], [] try: if cint( frappe.db.get_value("Integration Service", "Dropbox", "enabled")): did_not_upload, error_log = backup_to_dropbox() if did_not_upload: raise Exception send_email(True, "Dropbox") except Exception: file_and_error = [ " - ".join(f) for f in zip(did_not_upload, error_log) ] error_message = ("\n".join(file_and_error) + "\n" + frappe.get_traceback()) frappe.errprint(error_message) send_email(False, "Dropbox", error_message)
def get_rutas_recorrido(user, date): rutas = frappe.get_all('Recorrido', fields=['lat', 'lng', 'creation'], filters={ 'user': user, 'fecha': date }, order_by='creation') frappe.errprint('Rutas del Recorrido') frappe.errprint(rutas) feature = """ { "type": "FeatureCollection" , "features":[ { "type" : "Feature","properties":{},"geometry":{"type":"LineString","coordinates": [ """ for i in rutas: feature += """ [ """ + str(i.lng) + """,""" + str(i.lat) + """ ] """ if i == rutas[-1]: feature += """ ]}}]}""" else: feature += """ , """ return feature
def make_dic(self): fields = [] depends_on = "dosage_type" + ":" + self.name for d in self.get('dosage_fields'): f_dic = { "fieldname": d.fieldname, "fieldtype": d.fieldtype, "label": d.label, "depends_on": depends_on } if d.options: opts = d.options.split("\n") #opt=json.dumps(opts) f_dic["options"] = opts fields.append(f_dic) return fields frappe.errprint(fields)
def validate(self): frappe.errprint("in the validate") from frappe.utils import money_in_words self.check_existing() if not (len(self.get("earning_details")) or len(self.get("deduction_details"))): self.get_emp_and_leave_details() else: self.get_leave_details(self.leave_without_pay) if not self.net_pay: self.calculate_net_pay() company_currency = get_company_currency(self.company) self.total_in_words = money_in_words(self.rounded_total, company_currency) set_employee_name(self)
def autoname(self): frappe.errprint("name") naming_method = frappe.db.get_value("HR Settings", None, "emp_created_by") if naming_method == 'Naming Series': name = make_autoname(self.naming_series + '.####') self.name = name + '-' + self.company elif naming_method == 'Employee Number': self.name = self.employee_number # naming_method = frappe.db.get_value("HR Settings", None, "emp_created_by") # if not naming_method: # throw(_("Please setup Employee Naming System in Human Resource > HR Settings")) # else: # if naming_method=='Naming Series': # self.name = make_autoname(self.naming_series + '.####') # elif naming_method=='Employee Number': # self.name = self.employee_number self.employee = self.name
def enterOperation(code, amount, date): frappe.errprint("llama") consumable = frappe.get_all('consumables', filters={'code': code}, fields=['name', 'amount']) if (consumable[0]['amount'] - amount < 0): frappe.msgprint("The amount requested exceeds the amount available.") else: updateItem = frappe.get_doc('consumables', item[0]['name']) doc = frappe.new_doc("use_of_consumables") doc.consumable = item[0]['name'] doc.amount = amount doc.date = date doc.submit() updateItem.amount = updateItem.amount - amount updateItem.save() frappe.msgprint("Registration done.") return 0
def execute(filters=None): if not filters: filters = {} columns = data = [] sql = "CALL `Asset Mobilization-Demobilization Data`({0},{1},{2},{3},{4},{5},{6},{7});".format( json.dumps(filters.get('company')), json.dumps(filters.get('cost_center')), json.dumps(filters.get('project')), json.dumps(filters.get('asset_category')), json.dumps(filters.get('asset_status')), json.dumps(filters.get('asset_id')), json.dumps(filters.get('start_date')), json.dumps(filters.get('end_date'))) frappe.errprint(str(sql)) result = frappe.db.sql(sql, as_dict=1) columns = get_columns(result) data = get_values_list(result) return columns, data
def create_new_itemgroup(i, content): frappe.errprint("in item_group") itemgroup = frappe.new_doc('Item Group') frappe.errprint(itemgroup) itemgroup.parent_item_group = 'All Item Groups' itemgroup.item_group_name = content[i].get('media') itemgroup.is_group = 'No' itemgroup.save() frappe.errprint(content[i]['media']) frappe.errprint(item_group.name) return itemgroup.name or 'Products'
def get_rate_and_tax_details(row, gstin): itm_det = {"txval": flt(row["taxable_value"], 2), "rt": row["rate"], "csamt": (flt(row.get("cess_amount"), 2) or 0) } # calculate rate num = 1 if not row["rate"] else "%d%02d" % (row["rate"], 1) rate = row.get("rate") or 0 # calculate tax amount added tax = flt((row["taxable_value"]*rate)/100.0, 2) frappe.errprint([tax, tax/2]) if row.get("customer_gstin") and gstin[0:2] == row["customer_gstin"][0:2]: itm_det.update({"camt": flt(tax/2.0, 2), "samt": flt(tax/2.0, 2)}) else: itm_det.update({"iamt": tax}) return {"num": int(num), "itm_det": itm_det}
def toDo(desc, person): frappe.errprint("llama") user = frappe.get_doc({"doctype" : "User", "email" : person}) frappe.errprint("desc" + person) frappe.errprint(user.email) doc = frappe.new_doc({ "doctype" : "ToDo", "description": desc, "owner": person }) frappe.errprint(doc) return doc.insert()
def get_configurator_attributes_values(user_name): if print_debug: frappe.errprint("get_configurator_attributes_values") if print_debug: frappe.errprint("get_configurator_attributes_values") if print_debug: frappe.errprint("user:"******"result:" + cstr(result)) return result
def totales_cierre(caja,apertura,cierre, filters=None): data = frappe.db.sql(""" select SUM(s.grand_total) as total from `tabSales Invoice` s where s.creation >= '%s' and s.creation <= '%s' and s.status = 'Paid' and s.caja = '%s' union select SUM(s.grand_total) as efectivo from `tabSales Invoice Payment` p, `tabSales Invoice` s WHERE s.name = p.parent AND p.mode_of_payment = "Efectivo" AND s.status = "Paid" AND s.creation >= '%s' AND s.creation <= '%s' AND s.caja = '%s' union select SUM(s.grand_total) as tarjetas from `tabSales Invoice Payment` p, `tabSales Invoice` s WHERE s.name = p.parent AND p.mode_of_payment = "Tarjetas de credito" AND s.status = "Paid" AND s.creation >= '%s' AND s.creation <= '%s' AND s.caja = '%s' """ % (apertura,cierre,caja,apertura,cierre,caja,apertura,cierre,caja), as_dict=1) frappe.errprint(data) return data
def ldap_login(user, pwd, provider=None): frappe.errprint([user, pwd]) ldap_authentication(user, pwd) #### LDAP LOGIN LOGIC ##### ldap_authentication(user, pwd) frappe.local.login_manager.user = user frappe.local.login_manager.post_login() # redirect! frappe.local.response["type"] = "redirect" # the #desktop is added to prevent a facebook redirect bug frappe.local.response[ "location"] = "/desk#desktop" if frappe.local.response.get( 'message') == 'Logged In' else "/" # because of a GET request! frappe.db.commit()
def calculate_values(accounts_by_name, gl_entries_by_account, period_list, accumulated_values, ignore_accumulated_values_for_fy): for entries in gl_entries_by_account.values(): for entry in entries: d = accounts_by_name.get(entry.account) for period in period_list: # check if posting date is within the period if entry.posting_date <= period.to_date: if (accumulated_values or entry.posting_date >= period.from_date) and \ (entry.fiscal_year == period.to_date_fiscal_year or not ignore_accumulated_values_for_fy): frappe.errprint( [entry.fiscal_year, period.to_date_fiscal_year]) d[period.key] = d.get(period.key, 0.0) + flt( entry.debit) - flt(entry.credit) if entry.posting_date < period_list[0].year_start_date: d["opening_balance"] = d.get("opening_balance", 0.0) + flt( entry.debit) - flt(entry.credit)