Ejemplo n.º 1
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])
Ejemplo n.º 2
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]
Ejemplo n.º 3
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,
            })
Ejemplo n.º 4
0
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
            })
Ejemplo n.º 5
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)
Ejemplo n.º 6
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)
Ejemplo n.º 7
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
Ejemplo n.º 8
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)
Ejemplo n.º 9
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