示例#1
0
def sync():
    # read temperature
    print("Reading sensor data...")
    sense = SenseHat()
    sense.clear()
    temperature = sense.get_temperature()
    temperature = round(temperature, 1)
    print("{} {}".format(temperature, temperature_unit))
    # read humidity
    humidity = sense.get_humidity()
    humidity = round(humidity, 1)
    if humidity > 100:
        humidity = 100.0
    print("{} {}".format(humidity, humidity_unit))
    # write data to ERP
    print("Logging into ERP {}...".format(server))
    client = FrappeClient(server, user, password)
    print("Creating sensor data...")
    doc = {"doctype": "Sensor data"}
    doc["date"] = strftime("%Y-%m-%d")
    doc["time"] = strftime("%H:%M")
    doc["sensor_name"] = sensor_name
    doc["value"] = temperature
    doc["unit"] = temperature_unit
    client.insert(doc)
    print("Inserted " + doc["sensor_name"])
示例#2
0
def main(username: str = None, password: str = None):
    while not username:
        username = input("Username: "******"print_format") as it:
        for entry in it:
            html = None

            if entry.name not in PRINT_FORMATS:
                continue

            with open(entry.path) as html_file:
                html = html_file.read()

            client.update({
                "doctype": "Print Format",
                "name": PRINT_FORMATS.get(entry.name),
                "html": html,
                "css": css,
            })
示例#3
0
def bioconnect(bioip, attdate, attdate1):
    conn = None
    client = FrappeClient("https://erpmaxdclghana.com", "Administrator",
                          "S3kur1tiGH")
    bioip = bioip.split(":")
    zk = ZK(bioip[1], port=4370)
    try:
        conn = zk.connect()
        curdate = datetime.now().date()
        attendance = conn.get_attendance()
        for att in attendance:
            biodate = att.timestamp.date()
            userid = att.user_id
            if biodate >= attdate and biodate <= attdate1:
                biotime = att.timestamp.time()
                emp = client.get_value("Employee", ["name", "employee_number"],
                                       {
                                           "biometric_id": userid,
                                           "status": "Active"
                                       })
                if emp:
                    fetch_attendance(client, emp["name"], biodate, biotime)

    except Exception as e:
        print e
        messagebox.showinfo('Error', e)
def main():
    password = getpass()
    username = input('Username: '******'print_format') as it:
        for entry in it:
            html = None

            if entry.name not in PRINT_FORMATS:
                continue

            with open(entry.path) as html_file:
                html = html_file.read()

            client.update({
                'doctype': 'Print Format',
                'name': PRINT_FORMATS.get(entry.name),
                'html': html,
                'css': css
            })
示例#5
0
 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")
示例#6
0
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])
示例#7
0
def sync_master_after_submit(self, method):
    server_tujuan = frappe.db.get_single_value("Sync Server Settings",
                                               "server_tujuan")
    clientroot = FrappeClient(server_tujuan, "Administrator", "admin")

    # frappe.throw(clientroot.get_doc("Company","Jungle"))
    docu_tujuan = clientroot.get_value(self.doctype, "name",
                                       {"name": self.name})

    doc = frappe.get_doc(self.doctype, self.name)

    kolom_parent_after_submit = frappe.db.sql(""" SELECT td.fieldname
	FROM `tabDocField` td
	WHERE parent = "{}" 
	AND allow_on_submit = 1
	GROUP BY td.`fieldname`
	ORDER BY OPTIONS; """.format(self.doctype))

    pr_doc = {}
    for rowkolom in kolom_parent_after_submit:
        if str(rowkolom[0]) != "docstatus":
            if str(doc.get(str(rowkolom[0]))) != "None":
                if not docu_tujuan:
                    pr_doc.update({
                        (rowkolom[0]): str(doc.get(str(rowkolom[0])))
                    })
                elif str(rowkolom[0]) != "creation" and str(
                        rowkolom[0]) != "modified":
                    pr_doc.update({
                        (rowkolom[0]): str(doc.get(str(rowkolom[0])))
                    })

    pr_doc.update({"doctype": doc.doctype})
    pr_doc.update({"name": doc.name})
    # pr_doc_items = []
    # for temp_baris_item in self.uoms :
    # 	pr_doc_items.append({
    # 		"uom" : temp_baris_item.uom,
    # 		"conversion_factor" : temp_baris_item.conversion_factor,

    # 	})
    # pr_doc.update({ "uoms": pr_doc_items })
    # stringdoc = (str(pr_doc)).replace(" u'","'")
    # stringdoc = stringdoc.replace("'", '"')
    # stringdoc = stringdoc.replace("'", '"')
    # stringdoc = stringdoc.replace("{u", "{")

    # frappe.throw(stringdoc)
    # d = json.dumps(stringdoc)

    # frappe.throw(str(pr_doc))

    docu_tujuan = clientroot.get_value(self.doctype, "name",
                                       {"name": self.name})
    if docu_tujuan:
        clientroot.update(pr_doc)
    else:
        clientroot.insert(pr_doc)
示例#8
0
	def __init__(self):
		accessDetails = open('/home/hemant/access.txt')
		aD = json.loads(accessDetails.read())
		#print client
		self.client = FrappeClient(aD['url'],aD['username'],aD['password'])
		#FrappeClient(aD['url'],aD['username'],aD['password'])
		self.settingObj = self.client.get_api("varmani.getMTNServiceSettings")
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%"]]'])
示例#10
0
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%"]]'])
示例#11
0
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]
示例#12
0
 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")
示例#13
0
def main():
    log.startLogging(sys.stdout)
    log.msg("Start your engines...")

    accessDetails = open("/home/hemant/access.txt")
    aD = json.loads(accessDetails.read())
    client = FrappeClient(aD["url"], aD["username"], aD["password"])
    settingObj = client.get_api("varmani.getMTNServiceSettings")

    getLoginMessage = (
        "<usereq USERNAME='******' PASSWORD='******' VERBOSITY='0'><subscribe NODE='.*' TRANSFORM='USSD' PATTERN='\*'/></usereq>END"
    )

    reactor.connectTCP(
        settingObj["ussd_server_socket_ip"], int(settingObj["ussd_server_socket_port"]), EchoClientFactory()
    )
    reactor.run()
示例#14
0
def sync_role_master(self, method):
    # /home/frappe/frappe-bench/apps/frappe/frappe/core/doctype/role row 14, after insert WARNING
    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})
    doc = frappe.get_doc(self.doctype, self.name)
    pr_doc = {}
    pr_doc.update({"doctype": "Role"})
    pr_doc.update({"role_name": doc.role_name})
    if docu_tujuan:
        clientroot.update(pr_doc)
    else:
        clientroot.insert(pr_doc)
示例#15
0
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)
示例#16
0
def http_connection():

    connection = []
    try:
        connection = FrappeClient("https://meraki.erp.co.zm", "api",
                                  "Meraki55%%")

    except SocketTimeout as st:
        print("Connection to %s timed out. (timeout=%s)" %
              (st.host, st.timeout))
        connection = False

    except SocketError as e:
        # print("Failed to establish a new connection: %s" % e)
        print("Failed to establish a network connection")
        connection = False

    return connection
示例#17
0
def http_connection():

    connection = True

    try:
        connection = FrappeClient(settings.erpnext_host, settings.erpnext_user,
                                  settings.erpnext_password)

    except SocketTimeout as st:
        logging.warning("Connection to %s timed out. (timeout=%s)" %
                        (st.host, st.timeout))
        connection = False

    except SocketError as e:
        logging.warning("Failed to establish a network connection")
        connection = False

    return connection
示例#18
0
class MessageSerice(object):
	def __init__(self):
		accessDetails = open('/home/hemant/access.txt')
		aD = json.loads(accessDetails.read())
		#print client
		self.client = FrappeClient(aD['url'],aD['username'],aD['password'])
		#FrappeClient(aD['url'],aD['username'],aD['password'])
		self.settingObj = self.client.get_api("varmani.getMTNServiceSettings")

	def logMe(self, msg):
		localtime = datetime.datetime.now().replace(microsecond=0)
		message = "[" + localtime.strftime("%Y-%m-%d %H:%M:%S") + "] " + msg + "\r\n"
		sys.stdout.write(message)
		sys.stdout.flush()

	def sendSMS(self, msisdn, msg):
		responseMeg = "<usareq NODE='" + self.settingObj['sms_node'] + "' TRANSFORM='SUBMIT_SM' USERNAME='******'sms_username'] + "' PASSWORD='******'sms_password'] + "'><command><submit_sm><a_number>" + self.settingObj['sms_a_number'] + "</a_number><b_number>" + msisdn + "</b_number><service_type></service_type><message>"+ msg +"</message><registered_delivery></registered_delivery></submit_sm></command></usareq>"
		self.logMe("sms sent: " + msg + " to " + msisdn)
		r = requests.post(self.settingObj['message_url'], data = {'command': responseMeg} )
		return r

	def sendUSSD(self, sessionId, msisdn, msg, msgType):
		responseMeg = "<usareq NODE='" + self.settingObj['ussd_node'] + "' TRANSFORM='USSD' USERNAME='******'ussd_username'] + "' PASSWORD='******'ussd_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 getUSSDUsername(self):
		return self.settingObj['ussd_username']

	def getUSSDPassword(self):
		return self.settingObj['ussd_password']

	def getUSSDSocketIP(self):
		return self.settingObj['ussd_server_socket_ip']
		
	def getUSSDSocketPort(self):
		return int(self.settingObj['ussd_server_socket_port'])
		
	def getLoginMessage(self):
		return "<usereq USERNAME='******'ussd_username']+"' PASSWORD='******'ussd_password']+"' VERBOSITY='0'><subscribe NODE='.*' TRANSFORM='USSD' PATTERN='\*'/></usereq>END"
示例#19
0
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
示例#20
0
    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)
示例#21
0
import requests
from pandas.io.json import json_normalize
import numpy as np
from voucher import Voucher, JournalEntryAccount
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(
示例#22
0
from apiclient import discovery
import oauth2client
from oauth2client import client
from oauth2client import tools

try:
    import argparse
    flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args()
except ImportError:
    flags = None

SCOPES = 'https://www.googleapis.com/auth/spreadsheets.readonly'
CLIENT_SECRET_FILE = 'client_secret.json'
APPLICATION_NAME = 'Google Sheets API Python Quickstart'
client = FrappeClient("http://pds.intego.rw:8000", "administrator", "pds")


def get_credentials():

    home_dir = os.path.expanduser('~')
    credential_dir = os.path.join(home_dir, '.credentials')
    if not os.path.exists(credential_dir):
        os.makedirs(credential_dir)
    credential_path = os.path.join(
        credential_dir, 'sheets.googleapis.com-python-quickstart.json')

    store = oauth2client.file.Storage(credential_path)
    credentials = store.get()
    if not credentials or credentials.invalid:
        flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES)
示例#23
0
def sync_master(self, method):

    server_tujuan = frappe.db.get_single_value("Sync Server Settings",
                                               "server_tujuan")
    clientroot = FrappeClient(server_tujuan, "Administrator", "admin")

    # frappe.throw(clientroot.get_doc("Company","Jungle"))
    docu_tujuan = clientroot.get_value(self.doctype, "name",
                                       {"name": self.name})

    doc = frappe.get_doc(self.doctype, self.name)

    if doc.get("docstatus") == 1:
        return

    if doc.get("amended_from"):
        return

    kolom_parent = frappe.db.sql(
        """ SELECT COLUMN_NAME, DATA_TYPE FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME='tab{}' """
        .format(self.doctype))

    kolom_child = frappe.db.sql(""" SELECT td.fieldname, td.options
		FROM `tabDocField` td
		WHERE parent = "{}" AND fieldtype = "Table" 
		GROUP BY td.`fieldname`
		ORDER BY OPTIONS;
		 """.format(self.doctype))

    kolom_table = frappe.db.sql(
        """SELECT td.fieldname, ic.COLUMN_NAME, ic.DATA_TYPE  FROM `tabDocField` td 
		JOIN INFORMATION_SCHEMA.COLUMNS ic ON CONCAT("tab",td.`options`) = ic.`TABLE_NAME`
		WHERE parent = "{}" AND fieldtype = "Table"
		ORDER BY OPTIONS """.format(self.doctype))

    pr_doc = {}

    # for temp_baris_item in self.get("uoms") :
    # 	tampungan = temp_baris_item.get("uom")
    # 	frappe.throw(str(tampungan))

    for rowkolom in kolom_parent:
        if str(rowkolom[0]) != "docstatus":
            if str(doc.get(str(rowkolom[0]))) != "None":
                if str(rowkolom[1]) == "date" or str(
                        rowkolom[1]) == "datetime" or str(
                            rowkolom[1]) == "time":
                    if not docu_tujuan:
                        pr_doc.update({
                            (rowkolom[0]):
                            str(doc.get(str(rowkolom[0])))
                        })
                    elif str(rowkolom[0]) != "creation" and str(
                            rowkolom[0]) != "modified":
                        pr_doc.update({
                            (rowkolom[0]):
                            str(doc.get(str(rowkolom[0])))
                        })

                else:
                    pr_doc.update({(rowkolom[0]): (doc.get(str(rowkolom[0])))})

    for rowkolom in kolom_child:
        if self.get(rowkolom[0]):
            pr_doc_items = []
            for rowtable in self.get(rowkolom[0]):
                pr_doc_child = {}
                # frappe.throw(str(rowtable.get("uom")))
                for rowbaris in kolom_table:

                    if rowbaris[0] == rowkolom[0]:
                        if str(rowbaris[1]) != "docstatus" and str(
                                rowbaris[1]) != "name":
                            if str(rowtable.get(str(rowbaris[1]))) != "None":
                                if str(rowbaris[2]) == "date" or str(
                                        rowbaris[2]) == "datetime" or str(
                                            rowbaris[2]) == "time":
                                    if not docu_tujuan:
                                        pr_doc_child.update({
                                            rowbaris[1]:
                                            str(rowtable.get(str(rowbaris[1])))
                                        })
                                    elif str(
                                            rowbaris[1]) != "creation" and str(
                                                rowbaris[1]) != "modified":
                                        pr_doc_child.update({
                                            rowbaris[1]:
                                            str(rowtable.get(str(rowbaris[1])))
                                        })
                                else:
                                    pr_doc_child.update({
                                        rowbaris[1]:
                                        (rowtable.get(str(rowbaris[1])))
                                    })
                pr_doc_items.append(pr_doc_child)
            # frappe.throw(str(pr_doc_items))
            pr_doc.update({rowkolom[0]: pr_doc_items})

    pr_doc.update({"doctype": doc.doctype})
    # pr_doc_items = []
    # for temp_baris_item in self.uoms :
    # 	pr_doc_items.append({
    # 		"uom" : temp_baris_item.uom,
    # 		"conversion_factor" : temp_baris_item.conversion_factor,

    # 	})
    # pr_doc.update({ "uoms": pr_doc_items })
    # stringdoc = (str(pr_doc)).replace(" u'","'")
    # stringdoc = stringdoc.replace("'", '"')
    # stringdoc = stringdoc.replace("'", '"')
    # stringdoc = stringdoc.replace("{u", "{")

    # frappe.throw(stringdoc)
    # d = json.dumps(stringdoc)

    docu_tujuan = clientroot.get_value(self.doctype, "name",
                                       {"name": self.name})
    if docu_tujuan:
        clientroot.update(pr_doc)
    else:
        clientroot.insert(pr_doc)
示例#24
0
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
示例#25
0
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]])
示例#26
0
文件: test.py 项目: Varmani/varmani
from frappeclient import FrappeClient
import socket, select, string, sys
from messageService import MessageSerice

accessDetails = open("/home/hemant/access.txt")
aD = json.loads(accessDetails.read())

# print aD
# print aD['username']
# myMessenger = EmailService()
# localtime = time.asctime(time.localtime(time.time()))
# myMessenger.sendMessage("USSD Service started", "USSD Service started on " + localtime, "*****@*****.**")

# try:
msisdn = "27810378419"
client = FrappeClient(aD["url"], aD["username"], aD["password"])
customer = client.get_api("varmani.get_customer", "msisdn=" + msisdn)
if customer <> None:
    print customer
    print customer["full_name"]
    debt = client.get_api(
        "erpnext.accounts.utils.get_balance_on",
        "party_type=Customer&party=" + customer["customer"] + "&account=Debtors - VAR",
    )
    print "Welcome " + customer["full_name"] + " (" + str(debt * -1) + ")"
    result = client.get_api(
        "varmani.varmani.doctype.varmani_network.varmani_network.referral",
        "id=%s&serial=%s&referrer=%s" % ("6506040495087", "1733452431", customer["name"]),
    )

    new_varmani_network = {"doctype": "Varmani Network"}
示例#27
0
    #     "creation": "2016-11-10 14:28:48.729964",
    #     "modified": "2016-11-10 14:28:48.729964",
    #     "item_code": "C10-P",
    #     "doctype": "Bulk Pins",
    #     "vendor": "",
    #     "idx": 0,
    #     "pin": "***",
    #     "serial_number": "34785q",
    #     "owner": "Administrator",
    #     "docstatus": 0
    #   }
    # }

    sql = "INSERT INTO `tabBulk Pins` (name, creation, item_code, serial_number) VALUES (%s, %s, %s, %s)"
    # try:
    client = FrappeClient(aD['url'], aD['username'], aD['password'])
    print datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")

    items = client.get_api('varmani.varmani.doctype.bulk_pins.bulk_pins.get_items')
    # print items
    counter = 0

    def random_string(length):
        """generate a random string"""
        import string
        from random import choice
        return ''.join([choice(string.letters + string.digits) for i in range(length)])


    def do_stuff(q,i):
        while True:
示例#28
0
 def setUpClass(cls):
     cls.conn = FrappeClient(**test_config)
示例#29
0
    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")
示例#30
0
 def initialize(cls):
     settings = sg.UserSettings()
     Api.api = FrappeClient(settings['-server-'])
     Api.api.authenticate(settings['-key-'], settings['-secret-'])
     Api.api.get_list("Company")
示例#31
0
def add_faturas():

    print "Ficheiro clientes_dev.csv deve estar no /TMP"
    print "Formato do ficheiro Nomecliente,valor"
    print "Mudar o IP do Servidor"
    print "Mudar o Usuario e a Senha para Importar"

    #	client= FrappeClient("http://192.168.229.139:8000","*****@*****.**","demo123456789")
    client = FrappeClient("http://127.0.0.1:8000", "*****@*****.**",
                          "demo123456789")

    # loop no txt,csv and get Client, Valor
    # Lancamento de Devedores com IS OPENING=1

    with open('/tmp/clientes_dev.csv') as csvfile:
        readCSV = csv.reader(csvfile)
        print "Lendo o ficheiro..."

        for row in readCSV:

            if (len(row[0]) > 1):  #(row[0].strip() != "0"):

                nomecliente = row[0]
                valorcliente = row[1]
                print nomecliente
                print valorcliente

                try:
                    existe = frappe.get_doc("Customer", nomecliente)
                except frappe.DoesNotExistError:
                    print "Cliente ", unicode(
                        nomecliente.strip()), " nao existe"
                    print existe.name == nomecliente

                if (existe.name == nomecliente):
                    doc = {
                        "company":
                        "AngolaERP",
                        "conversion_rate":
                        1.0,
                        "currency":
                        "KZ",
                        "customer":
                        nomecliente,
                        "customer_name":
                        nomecliente,
                        "debit_to":
                        "31121000-Clientes Nacionais - CF",
                        "docstatus":
                        0,
                        "doctype":
                        "Sales Invoice",
                        "due_date":
                        frappe.utils.nowdate(),
                        "is_opening":
                        "Yes",
                        "is_pos":
                        0,
                        "is_recurring":
                        0,
                        "is_return":
                        0,
                        "items": [{
                            "cost_center": "Main - CF",
                            "item_code": "BFWDB",
                            "qty": 1.0,
                            "rate": flt(valorcliente)
                        }],
                        "status":
                        "Draft",
                        "submit_on_creation":
                        0,
                        "taxes": [{
                            "account_head":
                            "34210000-Imposto De Producao E Consumo - CF",
                            "charge_type": "On Net Total",
                            "cost_center": "Main - CF",
                            "description": "IPC &nbsp;%10",
                            "included_in_print_rate": 0,
                            "rate": 10.0
                        }],
                        "taxes_and_charges":
                        "Imposto de Consumo"
                    }

                    print doc

                    x = client.session.post(
                        "http://127.0.0.1:8000/api/resource/Sales Invoice",
                        data={"data": json.dumps(doc)})

                    print x

    client.logout()