def sync(): print("logging in...") client = FrappeClient("https://xxx.frappecloud.com", "xxx", "xxx") with open("jobs.csv", "rU") as jobsfile: reader = csv.reader(jobsfile, dialect='excel') for row in reader: if row[0] == "Timestamp": continue print("finding " + row[EMAIL]) name = client.get_value("Job Applicant", "name", {"email_id": row[EMAIL]}) if name: doc = client.get_doc("Job Applicant", name["name"]) else: doc = {"doctype": "Job Applicant"} doc["applicant_name"] = row[NAME] doc["email_id"] = row[EMAIL] doc["introduction"] = row[INTRODUCTION] doc["thoughts_on_company"] = row[THOUGHTS_ON_COMPANY] doc["likes"] = row[LIKES] doc["links"] = row[LINKS] doc["phone_number"] = row[PHONE] if doc.get("status") != "Rejected": doc["status"] = "Filled Form" if name: client.update(doc) print("Updated " + row[EMAIL]) else: client.insert(doc) print("Inserted " + row[EMAIL])
def sync(): print "logging in..." client = FrappeClient("https://xxx.frappecloud.com", "xxx", "xxx") with open("jobs.csv", "rU") as jobsfile: reader = csv.reader(jobsfile, dialect="excel") for row in reader: if row[0] == "Timestamp": continue print "finding " + row[EMAIL] name = client.get_value("Job Applicant", "name", {"email_id": row[EMAIL]}) if name: doc = client.get_doc("Job Applicant", name["name"]) else: doc = {"doctype": "Job Applicant"} doc["applicant_name"] = row[NAME] doc["email_id"] = row[EMAIL] doc["introduction"] = row[INTRODUCTION] doc["thoughts_on_company"] = row[THOUGHTS_ON_COMPANY] doc["likes"] = row[LIKES] doc["links"] = row[LINKS] doc["phone_number"] = row[PHONE] if doc.get("status") != "Rejected": doc["status"] = "Filled Form" if name: client.update(doc) print "Updated " + row[EMAIL] else: client.insert(doc) print "Inserted " + row[EMAIL]
class FrappeClientTest(unittest.TestCase): @httpretty.activate def setUp(self): httpretty.register_uri(httpretty.POST, "http://example.com", body='{"message":"Logged In"}', content_type="application/json" ) self.frappe = FrappeClient("http://example.com", "*****@*****.**", "password") @httpretty.activate def test_get_doc_with_no_doc_name(self): httpretty.register_uri( httpretty.GET, "http://example.com/api/resource/SomeDoc/", body='{"data": { "f1": "v1","f2": "v2"}}', content_type="application/json" ) res = self.frappe.get_doc( "SomeDoc", filters=[["Note", "title", "LIKE", "S%"]], fields=["name", "foo"]) self.assertEquals(res, {'f1': 'v1', 'f2': 'v2'}) request = httpretty.last_request() url = urlparse.urlparse(request.path) query_dict = urlparse.parse_qs(url.query) self.assertEquals(query_dict['fields'], [u'["name", "foo"]']) self.assertEquals(query_dict['filters'], [u'[["Note", "title", "LIKE", "S%"]]'])
def migrate(): print("logging in...") client = FrappeClient(HOST, USERNAME, PASSWORD) limit = 100 offset = 0 all_synced = True while (all_synced): employees_list = client.get_list('Employee', fields=['name', 'cnic_no'], filters={ 'name': '024232', 'status': 'Active', "image": ["<", "0"] }, limit_start=offset, limit_page_length=limit) if (len(employees_list) < limit): all_synced = False for employee in employees_list: try: emp = client.get_doc('Employee', employee["name"]) filename = "{0}.jpg".format(employee["cnic_no"]) img_str = get_base64_encoded_image( "source/pictures/{0}".format(filename)) if (img_str): file_path = upload_file(client=client, employee=employee["name"], filename=filename, filedata=img_str) if (file_path): emp = client.get_doc('Employee', employee["name"]) emp["image"] = file_path client.update(emp) except Exception as e: print('Failed to upload file for employee: {0} {1}'.format( employee["name"], e)) continue offset += limit
def sync_submit_master(self, method): if self.get("amended_from"): return server_tujuan = frappe.db.get_single_value("Sync Server Settings", "server_tujuan") clientroot = FrappeClient(server_tujuan, "Administrator", "admin") docu_tujuan = clientroot.get_value(self.doctype, "name", {"name": self.name}) if docu_tujuan: pr_doc = clientroot.get_doc(self.doctype, self.name) clientroot.submit(pr_doc)
import csv from frappeclient import FrappeClient client = FrappeClient("http://54.188.92.179/", "username", "******") DOC_NAME = "Sales Order" out_dict = dict() for doc in client.get_doc(DOC_NAME): items = client.get_doc(DOC_NAME, doc['name']).get('items') for item in items: if item.get('item_name') in out_dict.keys(): a = out_dict[item.get('item_name')] out_dict[item.get('item_name')] = a + item.get('qty') else: out_dict[item.get('item_name')] = item.get('qty') with open('SalesOrder.csv', mode='w') as csv_file: writer = csv.writer(csv_file, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL) writer.writerow(["Item Name", "Count"]) for key in out_dict.keys(): writer.writerow([key, out_dict[key]])
class EchoClientProtocol(Protocol): def dataReceived(self, data): root = ET.fromstring(data) for datablock in root.findall("datablock"): # lastTimeCheck = datetime.datetime.now().replace(microsecond=0) sessionid = datablock.find("sessionid").text msisdn = datablock.find("msisdn").text rootMsg = datablock.find("svcCode").text requestMsg = datablock.find("message").text.replace("*130*826*", "").replace("#", "") msgType = datablock.find("type").text localtime = time.asctime(time.localtime(time.time())) # ranNow = datetime.datetime.now().replace(microsecond=0) # saveTime = "timeRec=" + ranNow.strftime("%Y-%m-%d %H:%M:%S") # log.msg( # localtime + " | " + sessionid + " | " + msisdn + " | " + rootMsg + " | " + requestMsg + " | " + msgType + " | " + saveTime) # lastTimeCheck = datetime.datetime.now().replace(microsecond=0) t = Thread(target=self.process_message, args=(sessionid, msisdn, rootMsg, requestMsg, msgType)) t.start() # try: # lastTimeCheck = datetime.datetime.now().replace(microsecond=0) # self.client.post_api("varmani.setLastTime", saveTime) # # except Exception as e: # log.msg("Unexpected error:" + str(e)) def connectionMade(self): accessDetails = open("/home/hemant/access.txt") self.aD = json.loads(accessDetails.read()) self.client = FrappeClient(self.aD["url"], self.aD["username"], self.aD["password"]) self.settingObj = self.client.get_api("varmani.getMTNServiceSettings") getLoginMessage = ( "<usereq USERNAME='******' PASSWORD='******' VERBOSITY='0'><subscribe NODE='.*' TRANSFORM='USSD' PATTERN='\*'/></usereq>END" ) data = getLoginMessage self.transport.write(data.encode()) log.msg("Data sent {}".format("MTN logging message")) myMessenger = EmailService() # MessageSerice() mySMSer = MessageSerice() localtime = time.asctime(time.localtime(time.time())) myMessenger.sendMessage("USSD Service started", "USSD Service started on " + localtime, "*****@*****.**") mySMSer.sendSMS("27810378419", "USSD Service started on " + localtime) def connectionLost(self, reason): log.msg("Lost connection because {}".format(reason)) def process_message(self, sessionId, msisdn, rootMsg, requestMsg, msgType): self.client = FrappeClient(self.aD["url"], self.aD["username"], self.aD["password"]) # lastTimeCheck = datetime.datetime.now().replace(microsecond=0) session = self.record_message(sessionId, msisdn, rootMsg, requestMsg, msgType, "", "1") try: banned = self.client.get_api("varmani.isBanned", "msisdn=" + msisdn) except: banned = False message_type = "USER_REQUEST" if banned != True or banned == None: # print 'NOT banned' try: customer = self.client.get_api( "varmani.varmani.doctype.varmani_network.varmani_network.get_customer", "msisdn=" + msisdn ) # returns varmani network node if customer <> None: req_msg = requestMsg.split("*130*826") # print req_msg # print req_msg[len(req_msg)-1] if rootMsg != "*130*826#": # Speed dials options = requestMsg.split("*") # print str(options) if options[0] == "0": # Buy products pass elif options[0] == "1": # Refer - *ID*SERIALNUMBER try: id = options[1] # print id except: id = None message = "ID Number not provided or invalid" message_type = "PULL_REQ_CONFIRM" next_command = "ERROR" try: serial_number = options[2] # print serial_number except: serial_number = None message = "ID Number not provided or invalid" message_type = "PULL_REQ_CONFIRM" next_command = "ERROR" if id != None and serial_number != None: # print 'got here: ' +"id=%s&serial=%s" % (options[1],options[2]) result = self.client.get_api( "varmani.varmani.doctype.varmani_network.varmani_network.referral", "id=%s&serial=%s&referrer=%s" % (options[1], options[2], customer["name"]), ) message = result["message"] message_type = result["message_type"] next_command = result["next_command"] elif options[0] == "01": # Opt in - *ID try: id = options[1] # print id except: id = None message = "ID Number not provided or invalid" message_type = "PULL_REQ_CONFIRM" next_command = "ERROR" if id != None: result = self.client.get_api( "varmani.varmani.doctype.varmani_network.varmani_network.opt_in", "id=%s&msisdn=%s" % (options[1], msisdn), ) message = result["message"] message_type = result["message_type"] next_command = result["next_command"] customer = self.client.get_api( "varmani.varmani.doctype.varmani_network.varmani_network.get_customer", "msisdn=" + msisdn, ) # returns varmani network node # print customer elif options[0] == "2": # Get a new sim try: requester = options[1] # print id except: requester = None message = "Sim Number not provided or invalid" message_type = "PULL_REQ_CONFIRM" next_command = "ERROR" if requester != None: # print 'got here: ' +"id=%s&serial=%s" % (options[1],options[2]) result = self.client.get_api( "varmani.varmani.doctype.varmani_network.varmani_network.new_sim", "requester=%s&serial=%s" % (customer["name"], options[1]), ) message = result["message"] message_type = result["message_type"] next_command = result["next_command"] elif options[0] == "202": # new sim # print str(options[1]) result = self.client.get_api( "varmani.varmani.doctype.varmani_network.varmani_network.is_this_a_varmani_sim", "serial_no=%s" % (str(options[1])), ) # print str(result) if result == None: message = "You have not provided a Varmani Sim." else: result = self.client.get_api( "varmani.varmani.doctype.varmani_network.varmani_network.is_this_sim_sold", "serial_no=%s" % (str(options[1])), ) # print str(result) if result == None: message = "Sim is available" else: message = "Sim already sold" message_type = "PULL_REQ_CONFIRM" next_command = "INTERNAL" elif options[0] == "3": # Balance debt = self.client.get_api( "erpnext.accounts.utils.get_balance_on", "party_type=Customer&party=" + customer["customer"], ) # +"&account=Debtors - VAR") message = "Your balance is " + str(debt * -1) message_type = "PULL_REQ_CONFIRM" next_command = "BALANCE" elif options[0] == "33": pass elif options[0] == "4": # Reset Pin pass elif options[0] == "111": # Sell a new sim to a Varmani Customer pass elif options[0] == "99": # Special option for internal use only pass elif options[0] == "911": # Helpdesk request by Varmani Customer pass else: message = "Unknown request: " + requestMsg message_type = "PULL_REQ_CONFIRM" next_command = "ERROR" else: if session["command"] == "": debt = self.client.get_api( "erpnext.accounts.utils.get_balance_on", "party_type=Customer&party=" + customer["customer"], ) # +"&account=Debtors - VAR") message = "Welcome " + customer["full_name"] + ", please provide your pin." message_type = "USER_REQUEST" next_command = "PIN" if session["command"] == "PIN": # print 'msisdn="%s"&pin="%s"' %(msisdn, requestMsg) pin_verified = self.client.get_api( "varmani.varmani.doctype.varmani_network.varmani_network.verify_varmani_customer_pin", "msisdn=%s&pin=%s" % (msisdn, requestMsg), ) # print pin_verified if pin_verified == True: message = "Menu\n0- Buy a Varmani Product\n1- Refer Others\n2- Add a new sim to your account\n3- My Account Balance\n4- Reset your pin\nNeed Help? Dial *130*826*911#" message_type = "USER_REQUEST" next_command = "BUY" else: message = "Pin NOT verify, please try again." message_type = "USER_REQUEST" next_command = "PIN" elif session["command"] == "BUY": if requestMsg == "0": # buy product message = "Which product would you like to buy\n1) Airtime\n2) Electricity (Coming Soon)\nNeed Help? Dial *130*826*911#" message_type = "USER_REQUEST" next_command = "BUY" elif requestMsg == "1": # refer message = "You are buying\n Airtime\nNeed Help? Dial *130*826*911#" message_type = "PULL_REQ_CONFIRM" next_command = "SELECT" elif requestMsg == "2": # new sim message = "You are buying\n Electricity (Coming Soon)\nNeed Help? Dial *130*826*911#" message_type = "PULL_REQ_CONFIRM" next_command = "SELECT" elif requestMsg == "3": # balance debt = self.client.get_api( "erpnext.accounts.utils.get_balance_on", "party_type=Customer&party=" + customer["customer"], ) # +"&account=Debtors - VAR") message = "Your balance is " + str(debt * -1) message_type = "PULL_REQ_CONFIRM" next_command = "MENU" elif requestMsg == "4": # reset pin pass elif requestMsg == "99": # only for varmani pass elif session["command"] == "ID_TYPE": pass elif session["command"] == "ID_NUMBER": pass elif session["command"] == "SIMNUM": pass elif session["command"] == "SELECT": pass elif session["command"] == "SENDTO": pass elif session["command"] == "LOADTO": pass elif session["command"] == " AMOUNT": pass elif session["command"] == "CONFIRM_VEND": message_type = "PULL_REQ_CONFIRM" # print customer # print customer["full_name"] # print message # print message_type # print next_command # print message # print message_type # print next_command self.send_ussd(sessionId, msisdn, message, message_type) # 'USER_REQUEST')PULL_REQ_CONFIRM self.record_message(sessionId, msisdn, rootMsg, message, message_type, next_command, "0") else: req_msg = requestMsg.split("*130*826") # print req_msg # print req_msg[len(req_msg)-1] if rootMsg != "*130*826#": # Speed dials options = requestMsg.split("*") if options[0] == "01": # opt in - *ID try: id = options[1] # print id except: id = None message = "ID Number not provided or invalid" message_type = "PULL_REQ_CONFIRM" next_command = "ERROR" if id != None: customer = self.client.get_api( "varmani.varmani.doctype.varmani_network.varmani_network.get_customer", "id=" + id ) # returns varmani network node # print customer if customer <> None: # print 'got here: ' +"id=%s&serial=%s" % (options[1],options[2]) result = self.client.get_api( "varmani.varmani.doctype.varmani_network.varmani_network.opt_in", "id=%s&msisdn=%s" % (options[1], msisdn), ) message = result["message"] message_type = result["message_type"] next_command = result["next_command"] self.send_ussd( sessionId, msisdn, message, message_type ) # 'USER_REQUEST')PULL_REQ_CONFIRM self.record_message( sessionId, msisdn, rootMsg, message, message_type, next_command, "0" ) else: # print 'No customer with msisdn=' + msisdn + ' found.' self.record_message( sessionId, msisdn, rootMsg, "No customer with msisdn=" + msisdn + " found.", msgType, "", "0", ) else: # print 'No customer with msisdn=' + msisdn + ' found.' self.record_message( sessionId, msisdn, rootMsg, "No customer with msisdn=" + msisdn + " found.", msgType, "", "0", ) except: # send_ussd(sessionId,msisdn,'Not Authorised!','PULL_REQ_CONFIRM') # print(sys.exc_info()[0]) self.record_message(sessionId, msisdn, rootMsg, "Not Authorised!", msgType, "", "0") # localtime = time.asctime(time.localtime(time.time())) # current = datetime.datetime.now().replace(microsecond=0) # diff = current - ranNow # seconds = diff.total_seconds() # lastTimeCheck = datetime.datetime.now().replace(microsecond=0) seconds = 0 # currentTime = datetime.datetime.now() # diffTime = currentTime - lastTimeCheck # secondsTime = diffTime.total_seconds() # print 'sending message',secondsTime # lastTimeCheck = datetime.datetime.now().replace(microsecond=0) # currentTime = datetime.datetime.now() # diffTime = currentTime - lastTimeCheck # secondsTime = diffTime.total_seconds() # print 'Storing sessiong message', secondsTime else: # send_ussd(sessionId,msisdn,'Not Authorised!','PULL_REQ_CONFIRM') self.record_message(sessionId, msisdn, rootMsg, "Banned!", msgType, "", "0") def send_ussd(self, sessionId, msisdn, msg, msgType): responseMeg = ( "<usareq NODE='" + self.settingObj["ussd_node"] + "' TRANSFORM='USSD' USERNAME='******' PASSWORD='******' VERBOSITY='2'><command><ussd_response><sessionid>" + sessionId + "</sessionid><type>" + msgType + "</type><msisdn>" + msisdn + "</msisdn><message>" + msg + "</message></ussd_response></command></usareq>" ) r = requests.post(self.settingObj["message_url"], data={"command": responseMeg}) def record_message(self, sessionid, msisdn, rootMsg, requestMsg, msgType, last_command, direction): # self.client = FrappeClient("https://www.varmani.co.za","administrator","gauranga") # print last_command try: nameMSISDN = self.client.get_value("MSISDN Communications", "name", {"msisdn": msisdn}) if nameMSISDN: docMSISDN = self.client.get_doc("MSISDN Communications", nameMSISDN["name"]) else: docMSISDN = {"doctype": "MSISDN Communications"} name = self.client.get_value("USSD Session", "name", {"ussd_sessionid": sessionid}) if name: doc = self.client.get_doc("USSD Session", name["name"]) # oldmessages = doc["messages"] doc["messages"] += "|- %s -|- %s -|- %s -|- %s -|- %s -|\n" % ( datetime.datetime.now().replace(microsecond=0).strftime("%Y-%m-%d %H:%M:%S"), direction, msisdn, msgType, requestMsg, ) # doc["messages"] = oldmessages if last_command != "": doc["command"] = last_command else: doc = {"doctype": "USSD Session"} doc["command"] = "" doc["messages"] = "|- %s -|- %s -|- %s -|- %s -|- %s -|\n" % ( datetime.datetime.now().replace(microsecond=0).strftime("%Y-%m-%d %H:%M:%S"), direction, msisdn, msgType, requestMsg, ) docMSISDN["msisdn"] = msisdn doc["ussd_sessionid"] = sessionid doc["msisdn"] = msisdn doc["root_message"] = rootMsg localtime = datetime.datetime.now().replace(microsecond=0) doc["date"] = localtime.strftime("%Y-%m-%d %H:%M:%S") try: docMSISDN["ussd_sessions"].append(doc) except: docMSISDN["ussd_sessions"] = [] docMSISDN["ussd_sessions"].append(doc) # print(docMSISDN) # print "this far" docMSISDN["session_count"] = self.client.get_api("varmani.USSDMessageCount", "msisdn=" + msisdn) if nameMSISDN: self.client.update(docMSISDN) else: self.client.insert(docMSISDN) return doc except: print("something went wrong") print(sys.exc_info()[0]) return None
from frappeclient import FrappeClient import pandas import json try: client = FrappeClient("https://erp.tecton.cl", "*****@*****.**", "tecton") except: print("ERROR LOGEARSE AL ERP") raise with open("output.json", "r") as read_file: voucher = json.load(read_file) print(client.get_doc('Journal Entry', 'JV-16352')) headers = { 'content-type': 'application/json', 'auth_token': 'daSY92P7JMXZzFBkZCDDMYiU' } url = 'https://tecton.buk.cl/api/v1/accounting/export?month=10&year=2019&company_id=76.407.152-2' r = requests.get(url, headers=headers) buk = json.loads(r.content) data = json_normalize( buk["data"]["76.407.152-2"]["Constructora Tecton S.p.A."]) data["deber"] = data["deber"].replace({'': 0}) data["haber"] = data["haber"].replace({'': 0})