Ejemplo n.º 1
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")
Ejemplo n.º 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,
            })
Ejemplo n.º 3
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"])
Ejemplo n.º 4
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)
Ejemplo n.º 5
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.º 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])
Ejemplo n.º 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)
Ejemplo n.º 8
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)
Ejemplo n.º 9
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.º 10
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
Ejemplo n.º 11
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
Ejemplo n.º 12
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.º 13
0
 def setUpClass(cls):
     cls.conn = FrappeClient(**test_config)
Ejemplo n.º 14
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)
Ejemplo n.º 15
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.º 16
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(
Ejemplo n.º 17
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]])
Ejemplo n.º 18
0
 def initialize(cls):
     settings = sg.UserSettings()
     Api.api = FrappeClient(settings['-server-'])
     Api.api.authenticate(settings['-key-'], settings['-secret-'])
     Api.api.get_list("Company")
Ejemplo n.º 19
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()