Example #1
0
def add_stocks(items, file):
    for item in items:

        # if item["Location"] == "DCL House, Plot 1299 Fumilayo Ransome Kuti Way, Area 3, PMB 690 Garki, Abuja":
        #     to_warehouse = "DCLWarehouse - Abuja - DCL"
        # elif item[
        #     "Location"] == "DCL Laboratory Products Ltd, Plot 5 Block 4 Etal Avenue off Kudirat Abiola Way by NNPC Lagos NG - DCL":
        #     to_warehouse = "Lagos Warehouse - DCL"
        # else:
        to_warehouse = item["Location"]

        # def get_stock_value_from_bin(warehouse="DCLWarehouse - Abuja - DCL", item_code=item["item_code"]):
        bal = get_stock_value_from_bin(warehouse=to_warehouse,
                                       item_code=item["item_code"])
        print "          * * * * Check Bin * * * *"
        print "          " + str(bal[0][0]), item['qty']
        print "          " + item['item_code']
        date = None
        time = None
        if item["DatePaid"]:
            print "          ", item["DatePaid"].date(), item["DatePaid"].time(
            )
            date = item["DatePaid"].date()
            time = item["DatePaid"].time()
        elif item["OrderDate"]:
            date = item["OrderDate"].date()
            time = item["OrderDate"].time()

        if bal[0][0] < item['qty'] or bal[0][0] == None or bal[0][0] == 0:
            diff = 0
            if bal[0][0] != None:
                diff = bal[0][0]
            make_stock_entry(item_code=item["item_code"],
                             qty=abs(float(item["qty"]) - diff),
                             to_warehouse=to_warehouse,
                             valuation_rate=1,
                             remarks="This is affected by data import. " +
                             file,
                             posting_date=date,
                             posting_time=time,
                             set_posting_time=1,
                             inflow_file=file)
            frappe.db.commit()
            print "Stock entry created."
Example #2
0
def start_import(file):
    import csv
    import os
    current_customer = ""
    current_order = ""
    SI_dict = {}
    last_single_SI_dict = {}
    SI_items = []
    last_single_SI_items = []
    paid_and_fulfilled_items = []
    last_single_paid_and_fulfilled_items = []
    fulfilled_items = []
    last_single_fulfilled_items = []
    paid_items = []
    unpaid_items = []
    last_single_paid_items = []
    paid_pi = {}
    # input_file = csv.DictReader(open(os.path.dirname(os.path.abspath(__file__))+'/data/inFlow_PurchaseOrder_test.csv'))
    input_file = csv.DictReader(open(os.path.dirname(os.path.abspath(__file__))+'/data/'+file))

    # current_customer = input_file[0]["Customer"]

    income_accounts = "5111 - Cost of Goods Sold - DCL"
    # income_accounts = "Sales - J"
    cost_centers = "Main - DCL"
    # cost_centers = "Main - J"

    rows = list(input_file)
    total_paid = 0.0
    last_single_total_paid = 0.0
    # print rows
    totalrows = len(rows) - 1
    for i,row in enumerate(rows):
        # print row

        if row["InventoryStatus"] == "Quote":
            continue

        # if row["InventoryStatus"] == "Unfulfilled" and row["PaymentStatus"] == "Uninvoiced":
        #     continue

        skip_rows = ["SO-002811","SO-002812","SO-001720","SO-001721",
                     "SO-002106","SO-002439","SO-002933","SO-002823","SO-002917"]
        if row["OrderNumber"] in skip_rows:
            continue

        if row["Location"].strip():
            if row["Location"].strip() == "DCL House, Plot 1299 Fumilayo Ransome Kuti Way, Area 3, PMB 690 Garki, Abuja":
                to_warehouse = "DCLWarehouse - Abuja - DCL"
            elif row[
                "Location"].strip() == "DCL Laboratory Products Ltd, Plot 5 Block 4 Etal Avenue off Kudirat Abiola Way by NNPC Lagos NG":
                to_warehouse = "Lagos Warehouse - DCL"
            else:
                to_warehouse = row["Location"].strip() + " - DCL"
        else:
            to_warehouse = ""
            #make item non stock
            item_code1 = row["ItemName"].strip()
            if "Kerosene stove, four burner pressure type for use with 39L autoclave / steriliser." in item_code1:
                item_code1 = "Kerosene Stove"
                # elif "X-Annual comprehensive maintenance service of selectra analyzer located at St Mary's Catholic Hospital Gwagwalada.FCT Abuja" in item_code1:
                #     item_code1 = "X-Annual comprehensive maintenance service"
            elif "X-Annual comprehensive maintenance service" in item_code1:
                item_code1 = "X-Annual comprehensive maintenance service"
            frappe.db.sql("""UPDATE `tabItem` SET is_stock_item=1 WHERE item_code=%s""", (item_code1))
            frappe.db.commit()
            to_warehouse = "DCLWarehouse - Abuja - DCL"


        if row["Location"].strip():
            exists_cat = frappe.db.sql("""SELECT Count(*) FROM `tabWarehouse` WHERE warehouse_name=%s""", (row["Location"].strip()))
            # print exists_cat, row["Location"]
            if exists_cat[0][0] == 0:
                item_code = row["Location"]
                SI = frappe.get_doc({"doctype": "Warehouse",
                           "warehouse_name": item_code.strip()
                           })
                SI_created = SI.insert(ignore_permissions=True)
                frappe.db.commit()


        item_code1 = row["ItemName"].strip()
        # if row[
        #     "ItemName"] == "Kerosene stove, four burner pressure type for use with 39L autoclave / steriliser.\nSupplied specifically without top plate (ring) for use only with the autoclave / steam sterilizer.":
        if "Kerosene stove, four burner pressure type for use with 39L autoclave / steriliser." in item_code1:
            item_code1 = "Kerosene Stove"
        # elif "X-Annual comprehensive maintenance service of selectra analyzer located at St Mary's Catholic Hospital Gwagwalada.FCT Abuja" in item_code1:
        #     item_code1 = "X-Annual comprehensive maintenance service"
        elif "X-Annual comprehensive maintenance service" in item_code1:
            item_code1 = "X-Annual comprehensive maintenance service"
        exists_cat = frappe.db.sql("""SELECT Count(*) FROM `tabItem`
              WHERE item_code=%s or item_code=%s""", (item_code1,row["ItemDescription"].strip()))
        # print "                --------------------------------              "
        # print row
        # print exists_cat, item_code1, row["ItemDescription"]
        if exists_cat[0][0] == 0:
            SI = frappe.get_doc({"doctype": "Item",
                       "item_code": item_code1 or row["ItemDescription"].strip(),
                       "description": row["ItemDescription"].strip() or item_code1,
                       # "item_group": row["Category"].strip() + " Category"
                       "item_group": "All Item Groups"
                       })
            SI_created = SI.insert(ignore_permissions=True)
            frappe.db.commit()


        #CREATE SUPPLIER IF NOT EXISTS
        exists_supplier = frappe.db.sql("""SELECT Count(*) FROM `tabCustomer` WHERE name=%s""",(row["Customer"].strip()))
        if exists_supplier[0][0] == 0:
            frappe.get_doc({"doctype":"Customer","customer_name":row["Customer"].strip(),
                            "customer_group":"All Customer Groups","customer_type":"Company"}).insert()
            frappe.db.commit()





        if i==0:
            current_customer = row["Customer"].strip()
            current_order = row["OrderNumber"]
            dt = parser.parse(row["OrderDate"])
            currency = ""
            conversion_rate = 0.0
            if float(row["ExchangeRate"]) != 0.0 and float(row["ExchangeRate"]) != 1.0:
                currency = row["CurrencyCode"]
                conversion_rate = float(row["ExchangeRate"]) * 100000.00
            elif float(row["ExchangeRate"]) == 0.0 or float(row["ExchangeRate"]) == 1.0:
                currency = "NGN"
                conversion_rate = 0.0

            delivery_date = None
            if row["OrderDate"]:
                dt2 = parser.parse(row["OrderDate"])
                delivery_date = dt2.date()
            else:
                dt2 = None

            SI_dict = {"doctype": "Sales Order",
                       "title": current_customer,
                       "customer": current_customer,
                       "posting_date": dt.date(),
                       "schedule_date": dt.date(),  # TODO + 30 days
                       "transaction_date": dt.date(),
                       "due_date": delivery_date,
                       "delivery_date": delivery_date,
                       "items": SI_items,
                       "docstatus": 1,
                       "outstanding_amount": total_paid,
                       "name": row["OrderNumber"],
                       "OrderDate":dt,
                       "DatePaid":row["DatePaid"],
                       "inflow_remarks":row["OrderRemarks"],
                       "inflow_file":file,
                       "currency": currency,
                       "conversion_rate":conversion_rate,
                       "inflow_salesrep": row["SalesRep"],
                       "inflow_sales_person": row["Sales Person"],
                       "disable_rounded_total": 1,
                       "AmountPaid": row["AmountPaid"],
                       "PaymentStatus":row["PaymentStatus"]
                       }
        # print(current_customer,row["Vendor"],totalrows)
        print "                                  ",totalrows,i
        if current_customer != row["Customer"].strip() or current_customer != row["Customer"].strip() \
                or current_order!= row["OrderNumber"] or totalrows == i:


            if totalrows == i and current_customer == row["Customer"]:
                # print "LAST ROW!"
                item_code1 = row["ItemName"].strip()
                # if row[
                #     "ItemName"] == "Kerosene stove, four burner pressure type for use with 39L autoclave / steriliser.\nSupplied specifically without top plate (ring) for use only with the autoclave / steam sterilizer.":
                if "Kerosene stove, four burner pressure type for use with 39L autoclave / steriliser." in item_code1:
                    item_code1 = "Kerosene Stove"
                    # elif "X-Annual comprehensive maintenance service of selectra analyzer located at St Mary's Catholic Hospital Gwagwalada.FCT Abuja" in item_code1:
                    #     item_code1 = "X-Annual comprehensive maintenance service"
                elif "X-Annual comprehensive maintenance service" in item_code1:
                    item_code1 = "X-Annual comprehensive maintenance service"

                # print row["ItemName"]
                if item_code1:
                    SI_item = {
                        # "item_code": installment.item,  # test
                        "description": row["ItemDescription"].strip() or row["ItemName"],
                        "item_name": item_code1,
                        "item_code": item_code1,
                        # "rate": truncate(float(row["ItemSubtotal"]),2),
                        "rate": truncate(float(row["ItemUnitPrice"]),2),
                        "price_list_rate": truncate(float(row["ItemUnitPrice"]),2),
                        "conversion_factor": 1,
                        "uom": "Nos",
                        "expense_account": income_accounts,
                        "cost_center": cost_centers,
                        "qty": row["ItemQuantity"],
                        # "warehouse":row["Location"].strip() +" - DCL",
                        "warehouse":to_warehouse,
                        "InventoryStatus":row["InventoryStatus"],
                        "PaymentStatus":row["PaymentStatus"],
                        "OrderDate":row["OrderDate"]
                    }
                    SI_items.append(SI_item)

                if row["PaymentStatus"] in ["Uninvoiced"]:
                    paid_items.append({
                        # "item_code": installment.item,  # test
                        "description": row["ItemDescription"].strip() or row["ItemName"],
                        "item_name": item_code1,
                        "item_code": item_code1,
                        # "rate": truncate(float(row["ItemSubtotal"]),2),
                        "rate": truncate(float(row["ItemUnitPrice"]), 2),
                        "conversion_factor": 1,
                        "uom": "Nos",
                        "expense_account": income_accounts,
                        "cost_center": cost_centers,
                        "qty": abs(float(row["ItemQuantity"])),
                        # "warehouse": row["Location"].strip() + " - DCL",
                        "warehouse": to_warehouse,
                        "Location": to_warehouse,
                        "OrderDate": row["OrderDate"],
                        "DatePaid": row["DatePaid"],
                        "InventoryStatus": row["InventoryStatus"],
                        "PaymentStatus": row["PaymentStatus"]
                    })


                if row["InventoryStatus"] == "Fulfilled":
                    fulfilled_items.append({
                        "description": row["ItemDescription"].strip() or row["ItemName"],
                        "item_name": item_code1,
                        "item_code": item_code1,
                        "rate": truncate(float(row["ItemUnitPrice"]), 2),
                        "conversion_factor": 1,
                        "uom": "Nos",
                        "expense_account": income_accounts,
                        "cost_center": cost_centers,
                        "qty": abs(float(row["ItemQuantity"])),
                        # "warehouse": row["Location"].strip() + " - DCL",
                        "warehouse": to_warehouse,
                        "Location": to_warehouse,
                        "OrderDate": row["OrderDate"],
                        "DatePaid": row["DatePaid"],
                        "InventoryStatus": row["InventoryStatus"],
                        "PaymentStatus": row["PaymentStatus"]
                    })

                total_paid += float(row["ItemSubtotal"])

            elif totalrows == i:




                # print "LAST SINGLE ROW!"
                item_code1 = row["ItemName"].strip()
                # if row[
                #     "ItemName"] == "Kerosene stove, four burner pressure type for use with 39L autoclave / steriliser.\nSupplied specifically without top plate (ring) for use only with the autoclave / steam sterilizer.":
                if "Kerosene stove, four burner pressure type for use with 39L autoclave / steriliser." in item_code1:
                    item_code1 = "Kerosene Stove"
                    # elif "X-Annual comprehensive maintenance service of selectra analyzer located at St Mary's Catholic Hospital Gwagwalada.FCT Abuja" in item_code1:
                    #     item_code1 = "X-Annual comprehensive maintenance service"
                elif "X-Annual comprehensive maintenance service" in item_code1:
                    item_code1 = "X-Annual comprehensive maintenance service"

                if item_code1:
                    last_single_SI_items.append({
                        # "item_code": installment.item,  # test
                        "description": row["ItemDescription"].strip() or row["ItemName"],
                        "item_name": item_code1,
                        "item_code": item_code1,
                        # "rate": truncate(float(row["ItemSubtotal"]),2),
                        "rate": truncate(float(row["ItemUnitPrice"]), 2),
                        "price_list_rate": truncate(float(row["ItemUnitPrice"]), 2),
                        "conversion_factor": 1,
                        "uom": "Nos",
                        "expense_account": income_accounts,
                        "cost_center": cost_centers,
                        "qty": abs(float(row["ItemQuantity"])),
                        # "warehouse":row["Location"].strip() +" - DCL",
                        "warehouse": to_warehouse,
                        "Location": to_warehouse,
                        "InventoryStatus": row["InventoryStatus"],
                        "PaymentStatus": row["PaymentStatus"],
                        "OrderDate": row["OrderDate"]
                    })
                # print last_single_SI_items
                delivery_date = None
                if row["OrderDate"]:
                    dt2 = parser.parse(row["OrderDate"])
                    delivery_date = dt2.date()
                else:
                    dt2 = None
                dt = parser.parse(row["OrderDate"])
                if delivery_date < dt.date(): #Issue on Inflow SO-001000
                    # print "                          Issue SO-001000:", dt.date(), delivery_date
                    delivery_date = dt.date()
                last_single_SI_dict = {"doctype": "Sales Order",
                           "title": current_customer,
                           "customer": current_customer,
                           "posting_date": dt.date(),
                           "schedule_date": dt.date(),  # TODO + 30 days
                           "transaction_date": dt.date(),
                           "due_date": delivery_date,
                           "delivery_date": delivery_date,
                           "items": last_single_SI_items,
                           "docstatus": 1,
                           "outstanding_amount": total_paid,
                           "name": row["OrderNumber"],
                           "OrderDate": dt,
                           "DatePaid": row["DatePaid"],
                           "inflow_remarks": row["OrderRemarks"],
                           "inflow_file": file,
                           "currency": currency,
                           "conversion_rate": conversion_rate,
                           "inflow_salesrep": row["SalesRep"],
                            "inflow_sales_person": row["Sales Person"],
                           "disable_rounded_total": 1,
                           "AmountPaid": row["AmountPaid"],
                           "PaymentStatus": row["PaymentStatus"]
                           }

                if row["PaymentStatus"] in ["Uninvoiced"]:
                    last_single_paid_items.append({
                        # "item_code": installment.item,  # test
                        "description": row["ItemDescription"].strip() or row["ItemName"],
                        "item_name": item_code1,
                        "item_code": item_code1,
                        # "rate": truncate(float(row["ItemSubtotal"]),2),
                        "rate": truncate(float(row["ItemUnitPrice"]), 2),
                        "conversion_factor": 1,
                        "uom": "Nos",
                        "expense_account": income_accounts,
                        "cost_center": cost_centers,
                        "qty": abs(float(row["ItemQuantity"])),
                        # "warehouse": row["Location"].strip() + " - DCL",
                        "warehouse": to_warehouse,
                        "Location": to_warehouse,
                        "InventoryStatus": row["InventoryStatus"],
                        "PaymentStatus": row["PaymentStatus"]
                    })


                if row["InventoryStatus"] == "Fulfilled":
                    last_single_fulfilled_items.append({
                        "description": row["ItemDescription"].strip() or row["ItemName"],
                        "item_name": item_code1,
                        "item_code": item_code1,
                        "rate": truncate(float(row["ItemUnitPrice"]), 2),
                        "conversion_factor": 1,
                        "uom": "Nos",
                        "expense_account": income_accounts,
                        "cost_center": cost_centers,
                        "qty": abs(float(row["ItemQuantity"])),
                        # "warehouse": row["Location"].strip() + " - DCL",
                        "warehouse": to_warehouse,
                        "Location": to_warehouse,
                        "OrderDate": row["OrderDate"],
                        "DatePaid": row["DatePaid"],
                        "InventoryStatus": row["InventoryStatus"],
                        "PaymentStatus": row["PaymentStatus"]
                    })

                last_single_total_paid += float(row["ItemSubtotal"])


            SI_dict.update({"outstanding_amount":total_paid,
                            "inflow_file":file})




            exists_si = frappe.db.sql("""SELECT Count(*) FROM `tabSales Order`
                                                                WHERE name=%s""", (current_order))

            print "***************** " + current_order + " *******************"
            if exists_si[0][0] == 0 and SI_dict["items"]!= []:
                print "Sales Order does not exist!"
                print "Sales Order does not exist!"


                SI = frappe.get_doc(SI_dict)
                # print SI_dict
                print("                     CURRENT:",current_order,SI_dict["inflow_salesrep"],SI_dict["inflow_sales_person"])
                SI_created = SI.insert(ignore_permissions=True)


                for item in SI_dict["items"]:
                    datepaid = SI_dict['DatePaid']
                    if not datepaid:
                        datepaid = SI_dict["OrderDate"]
                    else:
                        datepaid = parser.parse(datepaid)
                    # pi.posting_date = datepaid.date()
                    # pi.posting_time = str(datepaid.time())
                    try:
                        make_stock_entry(item_code=item["item_code"], qty=item['qty'],
                                         to_warehouse=item["warehouse"],
                                         valuation_rate=1, remarks="This is affected by data import. " + file,
                                         posting_date=datepaid.date(),
                                         posting_time=str(datepaid.time()),
                                         set_posting_time=1, inflow_file=file)
                        frappe.db.commit()
                    except:
                        pass



                frappe.db.commit()
                #/home/jvfiel/frappe-v11/apps/frappe/frappe/model/rename_doc.py
                rename_doc("Sales Order",SI_created.name,current_order,force=True)
                frappe.db.commit()

                if paid_items:
                   make_invoice(paid_items,current_order,SI_dict)

            # if fulfilled_items:
            #     make_delivery(fulfilled_items, current_order, SI_dict)



            current_customer = row["Customer"].strip()
            current_order = row["OrderNumber"]
            dt = parser.parse(row["OrderDate"])
            SI_items = []

            currency = ""
            conversion_rate = 0.0
            if float(row["ExchangeRate"]) != 0.0 and float(row["ExchangeRate"]) != 1.0:
                currency = row["CurrencyCode"]
                conversion_rate = float(row["ExchangeRate"]) * 100000.00
            elif float(row["ExchangeRate"]) == 0.0 or float(row["ExchangeRate"]) == 1.0:
                currency = "NGN"
                conversion_rate = 0.0

            delivery_date = None
            if row["OrderDate"]:
                dt2 = parser.parse(row["OrderDate"])
                delivery_date = dt2.date()
            else:
                dt2 = None
            SI_dict = {"doctype": "Sales Order",
                       "title": current_customer,
                       "customer": current_customer,
                       "posting_date": dt.date(),
                       "schedule_date": dt.date(),  # TODO + 30 days
                       "transaction_date": dt.date(),
                       # "due_date": row["DueDate"],
                       "items": SI_items,
                       "docstatus": 1,
                       "outstanding_amount": total_paid,
                       "name": row["OrderNumber"],
                       "OrderDate":dt,
                       "DatePaid": row["DatePaid"],
                       "inflow_remarks": row["OrderRemarks"],
                       "inflow_file":file,
                       "currency": currency,
                       "conversion_rate": conversion_rate,
                       "due_date": delivery_date,
                       "delivery_date": delivery_date,
                       "inflow_salesrep": row["SalesRep"],
                       "inflow_sales_person": row["Sales Person"],
                       "disable_rounded_total": 1,
                       "AmountPaid": row["AmountPaid"],
                       "PaymentStatus": row["PaymentStatus"]
                       }
            paid_items = []
            fulfilled_items = []
            paid_and_fulfilled_items = []


        # else:
        item_code1 = row["ItemName"].strip()
        # if row[
        #     "ItemName"] == "Kerosene stove, four burner pressure type for use with 39L autoclave / steriliser.\nSupplied specifically without top plate (ring) for use only with the autoclave / steam sterilizer.":
        if "Kerosene stove, four burner pressure type for use with 39L autoclave / steriliser." in item_code1:
            item_code1 = "Kerosene Stove"
            # elif "X-Annual comprehensive maintenance service of selectra analyzer located at St Mary's Catholic Hospital Gwagwalada.FCT Abuja" in item_code1:
            #     item_code1 = "X-Annual comprehensive maintenance service"
        elif "X-Annual comprehensive maintenance service" in item_code1:
            item_code1 = "X-Annual comprehensive maintenance service"

        unitprice = 0.0
        if row["ItemUnitPrice"]:
            unitprice = float(row["ItemUnitPrice"])

        if item_code1:
            SI_item = {
                # "item_code": installment.item,  # test
                "description": row["ItemDescription"].strip() or row["ItemName"],
                "item_name": item_code1,
                "item_code": item_code1,
                # "warehouse": row["Location"].strip() +" - DCL",
                "warehouse": to_warehouse,
                # "rate": float(row["ItemUnitPrice"]),
                "rate": unitprice,
                "price_list_rate":unitprice,
                "conversion_factor":1,
                "uom":"Nos",
                "expense_account": income_accounts,
                "cost_center": cost_centers,
                "qty": abs(float(row["ItemQuantity"])),
                "InventoryStatus": row["InventoryStatus"],
                "PaymentStatus": row["PaymentStatus"],
                "OrderDate":row["OrderDate"]
            }
            SI_items.append(SI_item)


        if row["PaymentStatus"] in ["Uninvoiced"]:
            paid_items.append({
                "description": row["ItemDescription"].strip() or row["ItemName"],
                "item_name": item_code1,
                "item_code": item_code1,
                "rate": truncate(unitprice, 2),
                "price_list_rate": truncate(unitprice, 2),
                "conversion_factor": 1,
                "uom": "Nos",
                "expense_account": income_accounts,
                "cost_center": cost_centers,
                "qty": abs(float(row["ItemQuantity"])),
                "warehouse": to_warehouse,
                "Location": to_warehouse,
                "InventoryStatus": row["InventoryStatus"],
                "PaymentStatus": row["PaymentStatus"]
            })



        if row["InventoryStatus"] == "Fulfilled":
            fulfilled_items.append({
                "description": row["ItemDescription"].strip() or row["ItemName"],
                "item_name": item_code1,
                "item_code": item_code1,
                # "rate": truncate(float(row["ItemUnitPrice"]), 2),
                "rate": truncate(unitprice, 2),
                "price_list_rate": truncate(unitprice, 2),
                "conversion_factor": 1,
                "uom": "Nos",
                "expense_account": income_accounts,
                "cost_center": cost_centers,
                "qty": abs(float(row["ItemQuantity"])),
                # "warehouse": row["Location"].strip() + " - DCL",
                "warehouse": to_warehouse,
                "Location": to_warehouse,
                "OrderDate": row["OrderDate"],
                "DatePaid": row["DatePaid"],
                "InventoryStatus": row["InventoryStatus"],
                "PaymentStatus": row["PaymentStatus"]
            })

        total_paid +=float(row["ItemSubtotal"])

    SI_dict = last_single_SI_dict
    if last_single_SI_dict != {}:

        # print "* END *", current_order
        # print last_single_SI_dict["items"]
        SI = frappe.get_doc(last_single_SI_dict)
        # print SI_dict
        # print last_single_SI_dict

        for item in last_single_SI_dict["items"]:
            datepaid = SI_dict['DatePaid']
            if not datepaid:
                datepaid = SI_dict["OrderDate"]
            else:
                datepaid = parser.parse(datepaid)
            # pi.posting_date = datepaid.date()
            # pi.posting_time = str(datepaid.time())
            make_stock_entry(item_code=item["item_code"], qty=item['qty'],
                             to_warehouse=item["warehouse"],
                             valuation_rate=1, remarks="This is affected by data import. " + file,
                             posting_date=datepaid.date(),
                             posting_time=str(datepaid.time()),
                             set_posting_time=1, inflow_file=file)
            frappe.db.commit()

        print "***************** " + current_order + " *******************"
        if exists_si[0][0] == 0 and SI_dict["items"]!=[]:
            print "Sales Order does not exist!"
            print "Sales Order does not exist!"

            SI_created = SI.insert(ignore_permissions=True)
            frappe.db.commit()
            SI_created.submit()
            frappe.db.commit()
            rename_doc("Sales Order", SI_created.name, current_order, force=True)
            frappe.db.commit()

            if last_single_paid_items:
                make_invoice(last_single_paid_items,current_order,SI_dict)

        # if last_single_fulfilled_items:
        #     make_delivery(last_single_fulfilled_items,current_order,SI_dict)

    None
Example #3
0
def start_import():
    import csv
    import os
    current_customer = ""
    current_order = ""
    SI_dict = {}
    SI_items = []
    paid_and_fulfilled_items = []
    fulfilled_items = []
    paid_items = []
    input_file = csv.DictReader(open(os.path.dirname(os.path.abspath(__file__))+'/data/inFlow_StockLevels.csv'))

    # current_customer = input_file[0]["Customer"]

    income_accounts = "5111 - Cost of Goods Sold - DCL"
    # income_accounts = "Sales - J"
    cost_centers = "Main - DCL"
    # cost_centers = "Main - J"

    rows = list(input_file)
    total_paid = 0.0
    # print rows
    totalrows = len(rows)
    for i,row in enumerate(rows):
        # print row

           # from erpnext.stock.doctype.stock_entry.stock_entry_utils import make_stock_entry
            #/home/jvfiel/frappe-v11/apps/dcl/dcl/inflow_import/stock/__init__.py
        # for item in SI_items:
        #def get_stock_value_from_bin(warehouse="DCLWarehouse - Abuja - DCL", item_code=item["item_code"]):
        item = row
        print item
        bal = get_stock_value_from_bin(warehouse="DCLWarehouse - Abuja - DCL", item_code=item["Item"])
        print "          * * * * Check Bin * * * *"
        # print "          "+str(bal[0][0]),item['qty']
        # print "          "+item['item_code']
        # if bal[0][0] < item['qty'] or bal[0][0] == None or bal[0][0] == 0:
        #     diff = 0
        #     if bal[0][0] != None:
         #       diff = bal[0][0]
        to_warehouse = ""
        if row["Location"] == "DCL House, Plot 1299 Fumilayo Ransome Kuti Way, Area 3, PMB 690 Garki, Abuja":
            to_warehouse = "DCLWarehouse - Abuja - DCL"
        elif row["Location"] == "DCL Laboratory Products Ltd, Plot 5 Block 4 Etal Avenue off Kudirat Abiola Way by NNPC Lagos NG - DCL":
            to_warehouse = "Lagos Warehouse - DCL"
        else:
            to_warehouse = row["Location"] + " - DCL"
        if float(item["Quantity"]) < 1:

            exists_cat = frappe.db.sql("""SELECT Count(*) FROM `tabItem` WHERE item_code=%s""",
                                       (row["Item"].strip()))
            # print exists_cat
            if exists_cat[0][0] == 0:
                item_code = row["Item"]
                if row[
                    "Item"] == "Kerosene stove, four burner pressure type for use with 39L autoclave / steriliser.\nSupplied specifically without top plate (ring) for use only with the autoclave / steam sterilizer.":
                    item_code = "Kerosene Stove"
                item_dict = {"doctype": "Item",
                             "item_code": item_code.strip(),
                             "description": row["Item"],
                             # "item_group": row["Category"].strip() + " Category"
                             "item_group": "All Item Groups"
                             }
                SI = frappe.get_doc(item_dict)
                SI.insert(ignore_permissions=True)
                frappe.db.commit()

            make_stock_entry(item_code=item["Item"].strip(),qty=abs(float(item["Quantity"])),
                             to_warehouse=to_warehouse,
                             valuation_rate=1,remarks="This is affected by data import. StockLevels",
                             posting_date=parser.parse("3/15/2017"),
                             posting_time="00:00:00",
                             set_posting_time=1,inflow_file="inFlow_StockLevels.csv"
                             )
            frappe.db.commit()
Example #4
0
def add_stocks(items, file):
    for item in items:

        print item
        # if item["Location"] == "DCL House, Plot 1299 Fumilayo Ransome Kuti Way, Area 3, PMB 690 Garki, Abuja":
        #     to_warehouse = "DCLWarehouse - Abuja - DCL"
        # elif item[
        #     "Location"] == "DCL Laboratory Products Ltd, Plot 5 Block 4 Etal Avenue off Kudirat Abiola Way by NNPC Lagos NG - DCL":
        #     to_warehouse = "Lagos Warehouse - DCL"
        # else:
        to_warehouse = item["Location"]

        if item["OrderDate"]:
            OrderDate = parser.parse(item["OrderDate"])
        else:
            OrderDate = None

        if item["DatePaid"]:
            DatePaid = parser.parse(item["DatePaid"])
        else:
            DatePaid = None

        if item["DatePaid"]:
            # print "          ", item["DatePaid"].date(), item["DatePaid"].time()
            date = DatePaid.date()
            time = DatePaid.time()
        elif item["OrderDate"]:
            date = OrderDate.date()
            time = OrderDate.time()

        # def get_stock_value_from_bin(warehouse="DCLWarehouse - Abuja - DCL", item_code=item["item_code"]):
        bal = get_stock_value_on(warehouse=to_warehouse,
                                 posting_date=str(date),
                                 item_code=item["item_code"])
        print "          * * * * Check Bin * * * *"
        # print "          " + str(bal[0][0]), item['qty']
        print "          " + str(bal), item['qty']
        print "          " + item['item_code']

        if bal < item['qty'] or bal == None or bal == 0:
            diff = 0
            if bal != None:
                diff = bal

            print "              Diff:", item["qty"], diff, round(
                abs(float(item["qty"]) - diff), 2)
            qty = round(abs(float(item["qty"]) - diff), 2)
            # if qty < 1:
            qty = math.ceil(qty)
            make_stock_entry(item_code=item["item_code"],
                             qty=qty,
                             to_warehouse=to_warehouse,
                             valuation_rate=1,
                             remarks="This is affected by data import. " +
                             file,
                             posting_date=date,
                             posting_time=time,
                             set_posting_time=1,
                             inflow_file=file)
            frappe.db.commit()
            print "Stock entry created."
Example #5
0
def gecko_orders(page=1, replace=0, order_number="", skip_orders=[]):
    access_token = "6daee46c0b4dbca8baac12dbb0e8b68e93934608c510bb41a770bbbd8c8a7ca5"
    refresh_token = "76098f0a7f66233fe97f160980eae15a9a7007a5f5b7b641f211748d58e583ea"
    # tg = TradeGeckoRestClient(access_token, refresh_token)
    tg = TradeGeckoRestClient(access_token)
    # print tg.company.all()['companies'][0]
    if order_number == "":
        page_limit = 25
    else:
        page_limit = 2
    start_page = page

    while start_page < page_limit:

        print "########################### PAGE ", start_page, " ###########################"
        if not order_number:
            orders = tg.order.all(page=start_page, limit=250)['orders']
        else:
            orders = tg.order.filter(order_number=order_number)['orders']

        start_page += 1
        # print orders
        income_accounts = "5111 - Cost of Goods Sold - DCL"
        # income_accounts = "Sales - J"
        cost_centers = "Main - DCL"
        # cost_centers = "Main - J"

        for i, o in enumerate(orders):

            so_inv = None

            # if i+1 == 50:
            #     print "waiting..."
            #     time.sleep(20)

            # if o['invoices'] == []:
            #     print "No Invoice"
            #     continue

            # if o["status"] == "draft" or o['status'] == 'fulfilled': #draft,received,finalized,fulfilled
            #     continue
            # if o['payment_status'] == 'unpaid':
            #     continue
            skip = 0
            # if replace == 0:

            print "########################### PAGE ", start_page - 1, " ###########################"
            print o
            total_discount_amt = 0.0
            total_tax_amt = 0.0

            exists_po = frappe.db.sql(
                """SELECT Count(*) FROM `tabSales Order` WHERE name=%s""",
                (o['order_number']))
            if exists_po[0][0] > 0:
                skip = 1
                if replace == 1:
                    skip = 0
                if o['invoices'] != []:
                    for _inv in o['invoices']:
                        print "checking ", _inv['invoice_number']
                        exists_inv = frappe.db.sql(
                            """SELECT name FROM `tabSales Invoice` WHERE name=%s""",
                            (_inv['invoice_number']))
                        if exists_inv == ():  # check if the inv no. is correct
                            skip = 0
                            print "no inv or wrong name inv", _inv[
                                'invoice_number']
                        else:
                            # check if discounts where applied
                            exists_inv = frappe.get_doc(
                                "Sales Invoice", exists_inv[0][0])
                            total_discount_amt = 0.0
                            total_tax_amt = 0.0
                            xero_inv = test_xero(_inv['invoice_number'])
                            so_inv = xero_inv
                            # time.sleep(5)
                            for x in xero_inv[0]['LineItems']:
                                total_discount_amt += x['DiscountAmount']
                                total_tax_amt += x['TaxAmount']

                            if exists_inv.discount_amount < total_discount_amt:
                                skip = 0
                                print "no discount"

                            if total_tax_amt > 0.0:
                                skip = 0
                                print "no tax"

            elif exists_po[0][0] == 0:
                skip = 0  #dont skip
                print "SO not found"

            #
            # if o['order_number'] in skip_orders:
            #     continue

            if skip == 1:
                continue
            else:
                print "re-creating SO..."

            remove_imported_data(o["order_number"])
            sales_person_name = ""
            if o['assignee_id']:
                time.sleep(1)
                _user = tg.user.get(o['assignee_id'])
                if _user:
                    user = _user['user']
                    # print user

                    emp = frappe.db.sql(
                        """SELECT name FROM `tabEmployee`
                            WHERE first_name=%s and last_name=%s""",
                        (user['first_name'], user['last_name']))
                    emp_name = ""
                    if emp != ():
                        emp_name = emp[0][0]
                    else:
                        #create emp
                        emp_doc = frappe.get_doc({
                            "doctype":
                            "Employee",
                            "first_name":
                            user['first_name'],
                            "last_name":
                            user['last_name'],
                            "gender":
                            "Other",
                            "employee_number":
                            user['first_name'] + user['last_name'],
                            "date_of_birth":
                            frappe.utils.get_datetime().date(),
                            "date_of_joining": (frappe.utils.get_datetime() +
                                                timedelta(days=1)).date()
                        })
                        emp_doc.insert(ignore_permissions=True)
                        emp_name = emp_doc.name

                    sales_person = frappe.db.sql(
                        """SELECT name FROM `tabSales Person`
                                        WHERE name=%s""",
                        (user['first_name'] + ' ' + user['last_name']))
                    sales_person_name = ""
                    if sales_person != ():
                        sales_person_name = sales_person[0][0]
                    else:
                        sales_person_doc = frappe.get_doc({
                            "doctype":
                            "Sales Person",
                            "sales_person_name":
                            user['first_name'] + ' ' + user['last_name'],
                            "employee":
                            emp_name,
                            "parent_sales_person":
                            "Sales Team"
                        })
                        sales_person_doc.insert(ignore_permissions=True)
                        sales_person_name = sales_person_doc.name

            time.sleep(1)
            currency = tg.currency.get(o['currency_id'])['currency']
            created_at = parser.parse(o["created_at"])
            # received_at = parser.parse(o["received_at"])
            # due_at = parser.parse(o["due_at"])

            from dcl.tradegecko.fixerio import Fixerio
            fxrio = Fixerio(access_key='88581fe5b1c9f21dbb6f90ba6722d11c',
                            base=currency['iso'])
            currency_rate = fxrio.historical_rates(created_at.date())['rates']
            # print currency_rate['EUR'],currency['iso']
            # currency_rate = currency_rate[currency['iso']]
            currency_rate = currency_rate['GHS']

            # print o["order_number"]
            #
            # break
            SI_items = []
            time.sleep(1)
            to_warehouse = tg.location.get(o['stock_location_id'])['location']

            exists_warehouse = frappe.db.sql(
                """SELECT Count(*) FROM `tabWarehouse` WHERE warehouse_name=%s""",
                (to_warehouse['label']))
            if exists_warehouse[0][0] == 0:
                frappe.get_doc({
                    "doctype": "Warehouse",
                    "warehouse_name": to_warehouse['label']
                }).insert(ignore_permissions=True)
                frappe.db.commit()

            current_order = o["order_number"]
            tax_amount = 0.0
            for i in o['order_line_item_ids']:
                time.sleep(1)
                line_item = tg.order_line_item.get(i)['order_line_item']
                print line_item
                if line_item["tax_rate"]:
                    tax_amount += (round(float(line_item["price"])) * float(line_item["quantity"])) \
                                  * (float(line_item["tax_rate"]) / 100.00)
                    print(
                        round(float(line_item["price"])) *
                        float(line_item["quantity"]))
                    print(float(line_item["tax_rate"]) / 100.00)
                    print "Tax Amount", tax_amount

                # print line_item
                exists_cat = frappe.db.sql(
                    """SELECT Count(*),item_code,item_name,description FROM `tabItem`
                                        WHERE variant_id=%s""",
                    (line_item['variant_id']))
                item_code = ""
                item_name = ""
                item_description = ""
                if exists_cat[0][0] == 0:
                    time.sleep(1)
                    variant = tg.variant.get(line_item['variant_id'])
                    # print variant,line_item['variant_id']
                    # print line_item
                    if not variant:
                        variant = {
                            'product_name': line_item['label'],
                            'sku': line_item['label'],
                            'description': line_item['label']
                        }
                    else:
                        variant = variant["variant"]
                    # print variant
                    import re
                    clean_name = re.sub(r"[^a-zA-Z0-9]+", ' ',
                                        variant["product_name"])
                    if variant["sku"]:
                        item_code = re.sub(r"[^a-zA-Z0-9]+", ' ',
                                           variant["sku"]) or clean_name
                    else:
                        item_code = clean_name
                    item_name = clean_name
                    if "X960 Pipettor tip Thermo Scientific Finntip Flex  Filter sterile, free from DNA, " \
                       "DNase and RNasein vacuum sealed sterilized tip racks polypropylene tip," in item_code:
                        item_code = "X960 Pipettor tip Thermo Scientific Finntip Flex Filter"
                    if "X960 Pipettor tip Thermo Scientific Finntip Flex  Filter sterile, free from DNA, " \
                       "DNase and RNasein vacuum sealed sterilized tip racks polypropylene tip," in item_name:
                        item_name = "X960 Pipettor tip Thermo Scientific Finntip Flex Filter"
                    if "X960 Pipettor tip Thermo Scientific Finntip Flex Filter sterile free from DNA DNase " \
                       "and RNasein vacuum sealed sterilized tip racks polypropylene tip polyethylene matrix " in item_name:
                        item_name = "X960 Pipettor tip Thermo Scientific Finntip Flex Filter"

                    if "Stericup-GV, 0.22 " in item_code:
                        item_code = "Stericup-GV"
                    if "Stericup-GV, 0.22 " in item_name:
                        item_name = "Stericup-GV"

                    item_description = variant["description"]

                    find_item = frappe.db.sql(
                        """SELECT Count(*),item_code,item_name,description FROM `tabItem`
                                                       WHERE item_code=%s""",
                        (item_code))
                    if find_item[0][0] == 0:
                        item_dict = {
                            "doctype":
                            "Item",
                            "item_code":
                            item_code,
                            "item_name":
                            item_name,
                            "description":
                            variant["description"] or variant["product_name"],
                            "item_group":
                            "All Item Groups",
                            "variant_id":
                            line_item['variant_id']
                        }
                        # print item_dict
                        create_item = frappe.get_doc(item_dict)
                        create_item.insert(ignore_permissions=True)
                        frappe.db.commit()
                    else:
                        item_code = find_item[0][1]
                        item_name = find_item[0][2]
                        item_description = find_item[0][3]

                else:
                    item_code = exists_cat[0][1]
                    item_name = exists_cat[0][2]
                    item_description = exists_cat[0][3]

                # print variant
                SI_item = {
                    "description": item_description,
                    "item_name": item_name,
                    "item_code": item_code,
                    "rate": round(float(line_item["price"])),
                    "price_list_rate": round(float(line_item["price"])),
                    "conversion_factor": 1,
                    "uom": "Nos",
                    "expense_account": income_accounts,
                    "cost_center": cost_centers,
                    "qty": float(line_item["quantity"]),
                    "warehouse": to_warehouse['label'] + " - DCL",
                    "order_line_item_id": line_item["id"],
                    "variant_id": line_item['variant_id']
                    # "OrderDate": row["OrderDate"]
                }
                SI_items.append(SI_item)

            # print SI_items

            print SI_items
            if SI_items:
                time.sleep(1)
                supplier_company = tg.company.get(o['company_id'])['company']
                # print supplier_company

                # CREATE SUPPLIER IF NOT EXISTS
                exists_supplier = frappe.db.sql(
                    """SELECT Count(*) FROM `tabCustomer` WHERE name=%s""",
                    (supplier_company['name']))
                if exists_supplier[0][0] == 0:
                    frappe.get_doc({
                        "doctype": "Customer",
                        "customer_name": supplier_company['name'],
                        "customer_group": "All Customer Groups",
                        "customer_type": "Company",
                        "account_manager": "Dummy"
                    }).insert()
                    frappe.db.commit()

                sales_team = []
                if sales_person_name:
                    sales_team = [{
                        "sales_person": sales_person_name,
                        "allocated_percentage": 100.00
                    }]

                taxes = []
                if tax_amount or total_tax_amt:
                    tax_amount = tax_amount or total_tax_amt
                    taxes.append({
                        "charge_type": "Actual",
                        "tax_amount": tax_amount,
                        "account_head": "VAT - DCL",
                        "description": "tax"
                    })
                SI_dict = {
                    "doctype": "Sales Order",
                    "title": supplier_company['name'],
                    "customer": supplier_company['name'],
                    "posting_date": created_at.date(),
                    "schedule_date": created_at.date(),  # TODO + 30 days
                    "transaction_date": created_at.date(),
                    "due_date": created_at.date(),
                    "delivery_date": created_at.date(),
                    "items": SI_items,
                    "taxes": taxes,
                    "docstatus": status_map[o["status"]],
                    "inflow_file": current_order,
                    "currency": currency['iso'],
                    "conversion_rate": currency_rate,
                    "sales_team": sales_team,
                    "disable_rounded_total": 1
                }

                if o['status'] != "draft" and o['status'] != "active":
                    if o['invoices']:
                        for item in SI_items:
                            # check stocks first
                            # get_balance_qty_from_sle
                            # /home/jvfiel/frappe-v11/apps/erpnext/erpnext/stock/stock_balance.py
                            from erpnext.stock.stock_balance import get_balance_qty_from_sle, get_reserved_qty
                            get_bal = get_balance_qty_from_sle(
                                item["item_code"],
                                to_warehouse['label'] + " - DCL")
                            reserved_qty = get_reserved_qty(
                                item["item_code"],
                                to_warehouse['label'] + " - DCL")
                            # print item["item_code"], to_warehouse['label'] + " - DCL"
                            # print "rsvd qty ", reserved_qty
                            # print "bal", (float(get_bal))
                            # print "need", item['qty']
                            net_bal = (float(get_bal) - float(reserved_qty) -
                                       item['qty'])
                            # print "net bal", net_bal

                            reqd_qty = 0
                            if net_bal < 0:
                                # reqd_qty = float(item['qty']) - abs(float(item['qty']))
                                # print "itm qty", float(item['qty'])
                                reqd_qty = abs(net_bal)
                                # reqd_qty = abs(net_bal)+float(item['qty'])
                                # print "req qty", reqd_qty
                                make_stock_entry(
                                    item_code=item["item_code"],
                                    qty=reqd_qty,
                                    to_warehouse=to_warehouse['label'] +
                                    " - DCL",
                                    valuation_rate=1,
                                    remarks="This is affected by data import. ",
                                    posting_date=created_at.date(),
                                    posting_time=str(created_at.time()),
                                    set_posting_time=1,
                                    inflow_file=current_order)
                                frappe.db.commit()
                                # print "qty after stock ent", get_balance_qty_from_sle(item["item_code"],
                                #                                                       to_warehouse['label'] + " - DCL")
                            elif net_bal == 0:
                                reqd_qty = float(item['qty'])

                SI = frappe.get_doc(SI_dict)
                SI_created = SI.insert(ignore_permissions=True)
                frappe.db.commit()
                rename_doc("Sales Order",
                           SI_created.name,
                           o['order_number'],
                           force=True)
                frappe.db.commit()
                print "done submitting and renaming."

                if o['status'] != "draft" and o['status'] != "active":
                    if o['invoices']:
                        i = o['invoices'][0]
                        if so_inv == None:
                            inv = test_xero(i['invoice_number'])
                        else:
                            inv = so_inv
                        print SI_items
                        pi = make_invoice(o["order_number"], created_at, inv)
                        # print inv
                        frappe.db.commit()
                        rename_doc("Sales Invoice",
                                   pi.name,
                                   i['invoice_number'],
                                   force=True)
                        frappe.db.commit()
                        if inv[0]['AmountPaid']:
                            # print "paid", inv[0]['AmountPaid']
                            payment_request = make_payment_request(
                                dt="Sales Invoice",
                                dn=i['invoice_number'],
                                recipient_id="",
                                submit_doc=True,
                                mute_email=True,
                                use_dummy_message=True,
                                grand_total=float(inv[0]['AmountPaid']),
                                posting_date=created_at.date(),
                                posting_time=str(created_at.time()),
                                inflow_file=current_order)

                            # if SI_dict["PaymentStatus"] != "Invoiced":
                            payment_entry = frappe.get_doc(
                                make_payment_entry(payment_request.name))
                            payment_entry.posting_date = created_at.date()
                            payment_entry.posting_time = str(created_at.time())
                            payment_entry.set_posting_time = 1
                            # print "             ",pi.rounded_total,payment_entry.paid_amount
                            # if SI_dict["PaymentStatus"] == "Paid":
                            payment_entry.paid_amount = inv[0]['AmountPaid']

                            # else:
                            #     payment_entry.paid_amount = float(SI_dict["AmountPaid"])
                            payment_entry.inflow_file = current_order
                            payment_entry.submit()
                            # frappe.db.commit()
                        else:
                            print "unpaid"

                        for i in o['fulfillment_ids']:
                            time.sleep(1)
                            fills = tg.fulfillment_line_item.filter(
                                fulfillment_id=i)
                            # print fills
                            # print SI_items
                            fill_items = fills['fulfillment_line_items']
                            for j in fill_items:
                                # print j
                                for item in SI_items:
                                    if j['variant_id'] == item['variant_id']:
                                        j.update(item)
                            # print fill_items
                            # print " making delivery. "
                            # print " making delivery. "
                            # print " making delivery. "
                            # print " making delivery. "
                            # print " making delivery. "
                            # print fill_items
                            if fill_items:
                                make_delivery(fill_items, current_order,
                                              created_at)

                frappe.db.commit()
                # break
            # time.sleep(5)
        # time.sleep(20)
    print "DONE DONE DONE DONE DONE"
Example #6
0
def start_import(file):
    import csv
    import os
    current_customer = ""
    current_order = ""
    SI_dict = {}
    last_single_SI_dict = {}
    SI_items = []
    last_single_SI_items = []
    paid_and_fulfilled_items = []
    last_single_paid_and_fulfilled_items = []
    fulfilled_items = []
    last_single_fulfilled_items = []
    paid_items = []
    last_single_paid_items = []
    paid_pi = {}
    # input_file = csv.DictReader(open(os.path.dirname(os.path.abspath(__file__))+'/data/inFlow_PurchaseOrder_test.csv'))
    input_file = csv.DictReader(open(os.path.dirname(os.path.abspath(__file__))+'/data/'+file))

    # current_customer = input_file[0]["Customer"]

    income_accounts = "5111 - Cost of Goods Sold - DCL"
    # income_accounts = "Sales - J"
    cost_centers = "Main - DCL"
    # cost_centers = "Main - J"

    rows = list(input_file)
    total_paid = 0.0
    last_single_total_paid = 0.0
    # print rows
    totalrows = len(rows) - 1
    for i,row in enumerate(rows):
        # print row

        if row["Location"].strip():
            if row["Location"].strip() == "DCL House, Plot 1299 Fumilayo Ransome Kuti Way, Area 3, PMB 690 Garki, Abuja":
                to_warehouse = "DCLWarehouse - Abuja - DCL"
            elif row[
                "Location"].strip() == "DCL Laboratory Products Ltd, Plot 5 Block 4 Etal Avenue off Kudirat Abiola Way by NNPC Lagos NG - DCL":
                to_warehouse = "Lagos Warehouse - DCL"
            else:
                to_warehouse = row["Location"].strip() + " - DCL"
        else:
            to_warehouse = ""
            #make item non stock
            item_code1 = row["ItemName"].strip()
            frappe.db.sql("""UPDATE `tabItem` SET is_stock_item=1 WHERE item_code=%s""", (item_code1))
            frappe.db.commit()
            to_warehouse = "DCLWarehouse - Abuja - DCL"


        if row["Location"].strip():
            exists_cat = frappe.db.sql("""SELECT Count(*) FROM `tabWarehouse` WHERE warehouse_name=%s""", (row["Location"].strip()))
            # print exists_cat, row["Location"]
            if exists_cat[0][0] == 0:
                item_code = row["Location"]
                SI = frappe.get_doc({"doctype": "Warehouse",
                           "warehouse_name": item_code.strip()
                           })
                SI_created = SI.insert(ignore_permissions=True)
                frappe.db.commit()


        item_code1 = row["ItemName"].strip()
        # if row[
        #     "ItemName"] == "Kerosene stove, four burner pressure type for use with 39L autoclave / steriliser.\nSupplied specifically without top plate (ring) for use only with the autoclave / steam sterilizer.":
        if "Kerosene stove, four burner pressure type for use with 39L autoclave / steriliser." in item_code1:
            item_code1 = "Kerosene Stove"
        exists_cat = frappe.db.sql("""SELECT Count(*) FROM `tabItem` WHERE item_code=%s""", (item_code1))
        # print exists_cat
        if exists_cat[0][0] == 0:
            SI = frappe.get_doc({"doctype": "Item",
                       "item_code": item_code1,
                       "description": row["ItemDescription"],
                       # "item_group": row["Category"].strip() + " Category"
                       "item_group": "All Item Groups"
                       })
            SI_created = SI.insert(ignore_permissions=True)
            frappe.db.commit()


        #CREATE SUPPLIER IF NOT EXISTS
        exists_supplier = frappe.db.sql("""SELECT Count(*) FROM `tabSupplier` WHERE name=%s""",(row["Vendor"].strip()))
        if exists_supplier[0][0] == 0:
            frappe.get_doc({"doctype":"Supplier","supplier_name":row["Vendor"].strip(),
                            "supplier_group":"All Supplier Groups","supplier_type":"Company"}).insert()
            frappe.db.commit()





        if i==0:
            current_customer = row["Vendor"].strip()
            current_order = row["OrderNumber"]
            dt = parser.parse(row["OrderDate"])
            currency = ""
            conversion_rate = 0.0
            if float(row["ExchangeRate"]) != 0.0 and float(row["ExchangeRate"]) != 1.0:
                currency = row["CurrencyCode"]
                conversion_rate = float(row["ExchangeRate"])
            elif float(row["ExchangeRate"]) == 0.0 or float(row["ExchangeRate"]) == 1.0:
                currency = "NGN"
                conversion_rate = 0.0

            po_status = ""
            if row["InventoryStatus"] == "Fulfilled" and row["PaymentStatus"] == "Paid":
                po_status = "Completed"
            elif row["InventoryStatus"] == "Unfulfilled" and row["PaymentStatus"] == "Paid":
                po_status = "To Receive"
            elif row["InventoryStatus"] == "Fulfilled" and row["PaymentStatus"] == "Unpaid":
                po_status = "To Bill"
            SI_dict = {"doctype": "Purchase Order",
                       "title": current_customer,
                       "supplier": current_customer,
                       "posting_date": dt.date(),
                       "schedule_date": dt.date(),  # TODO + 30 days
                       "transaction_date": dt.date(),
                       # "due_date": row["DueDate"],
                       "po_status":po_status,
                       "due_date": dt.date(),
                       "items": SI_items,
                       # "docstatus": 1,
                       "outstanding_amount": total_paid,
                       "name": row["OrderNumber"],
                       "OrderDate":dt,
                       "inflow_remarks":row["OrderRemarks"],
                       "inflow_file":file,
                       "currency": currency,
                       "conversion_rate":conversion_rate
                       }
        # print(current_customer,row["Vendor"],totalrows)
        print "                                  ",totalrows,i
        if current_customer != row["Vendor"].strip() or current_customer != row["Vendor"].strip() \
                or current_order!= row["OrderNumber"] or totalrows == i:


            if totalrows == i and current_customer == row["Vendor"]:
                print "LAST ROW!"
                item_code1 = row["ItemName"].strip()
                # if row[
                #     "ItemName"] == "Kerosene stove, four burner pressure type for use with 39L autoclave / steriliser.\nSupplied specifically without top plate (ring) for use only with the autoclave / steam sterilizer.":
                if "Kerosene stove, four burner pressure type for use with 39L autoclave / steriliser." in item_code1:
                    item_code1 = "Kerosene Stove"

                print row["ItemName"]
                SI_item = {
                    # "item_code": installment.item,  # test
                    "description": row["ItemDescription"].strip() or row["ItemName"],
                    "item_name": item_code1,
                    "item_code": item_code1,
                    # "rate": truncate(float(row["ItemSubtotal"]),2),
                    "rate": truncate(float(row["ItemUnitPrice"]),2),
                    "conversion_factor": 1,
                    "uom": "Nos",
                    "expense_account": income_accounts,
                    "cost_center": cost_centers,
                    "qty": float(row["ItemQuantity"]),
                    "received_qty": float(row["ItemQuantity"]),
                    # "warehouse":row["Location"].strip() +" - DCL",
                    "warehouse":to_warehouse,
                    "InventoryStatus":row["InventoryStatus"],
                    "PaymentStatus":row["PaymentStatus"],
                    "OrderDate":row["OrderDate"]
                }
                SI_items.append(SI_item)

                if row["PaymentStatus"] == "Paid" and row["InventoryStatus"] == "Fulfilled":
                    paid_and_fulfilled_items.append({
                        # "item_code": installment.item,  # test
                        "description": row["ItemDescription"] or row["ItemName"],
                        "item_name": item_code1,
                        "item_code": item_code1,
                        # "rate": truncate(float(row["ItemSubtotal"]),2),
                        "rate": truncate(float(row["ItemUnitPrice"]), 2),
                        "conversion_factor": 1,
                        "uom": "Nos",
                        "expense_account": income_accounts,
                        "cost_center": cost_centers,
                        "qty": row["ItemQuantity"],
                        # "warehouse": row["Location"].strip() + " - DCL",
                        "warehouse": to_warehouse,
                        "InventoryStatus": row["InventoryStatus"],
                        "PaymentStatus": row["PaymentStatus"]
                    })

                if row["PaymentStatus"] == "Paid" and row["InventoryStatus"] != "Fulfilled":
                    paid_items.append({
                        # "item_code": installment.item,  # test
                        "description": row["ItemDescription"] or row["ItemName"],
                        "item_name": item_code1,
                        "item_code": item_code1,
                        # "rate": truncate(float(row["ItemSubtotal"]),2),
                        "rate": truncate(float(row["ItemUnitPrice"]), 2),
                        "conversion_factor": 1,
                        "uom": "Nos",
                        "expense_account": income_accounts,
                        "cost_center": cost_centers,
                        "qty": row["ItemQuantity"],
                        # "warehouse": row["Location"].strip() + " - DCL",
                        "warehouse": to_warehouse,
                        "InventoryStatus": row["InventoryStatus"],
                        "PaymentStatus": row["PaymentStatus"]
                    })

                if row["PaymentStatus"] != "Paid" and row["InventoryStatus"] == "Fulfilled":
                    fulfilled_items.append({
                        "description": row["ItemDescription"] or row["ItemName"],
                        "item_name": item_code1,
                        "item_code": item_code1,
                        "rate": truncate(float(row["ItemUnitPrice"]), 2),
                        "conversion_factor": 1,
                        "uom": "Nos",
                        "expense_account": income_accounts,
                        "cost_center": cost_centers,
                        "qty": row["ItemQuantity"],
                        # "warehouse": row["Location"].strip() + " - DCL",
                        "warehouse": to_warehouse,
                        "InventoryStatus": row["InventoryStatus"],
                        "PaymentStatus": row["PaymentStatus"]
                    })

                total_paid += float(row["ItemSubtotal"])

            elif totalrows == i:




                print "LAST SINGLE ROW!"
                item_code1 = row["ItemName"].strip()
                # if row[
                #     "ItemName"] == "Kerosene stove, four burner pressure type for use with 39L autoclave / steriliser.\nSupplied specifically without top plate (ring) for use only with the autoclave / steam sterilizer.":
                if "Kerosene stove, four burner pressure type for use with 39L autoclave / steriliser." in item_code1:
                    item_code1 = "Kerosene Stove"
                last_single_SI_items.append({
                    # "item_code": installment.item,  # test
                    "description": row["ItemDescription"].strip() or row["ItemName"],
                    "item_name": item_code1,
                    "item_code": item_code1,
                    # "rate": truncate(float(row["ItemSubtotal"]),2),
                    "rate": truncate(float(row["ItemUnitPrice"]), 2),
                    "conversion_factor": 1,
                    "uom": "Nos",
                    "expense_account": income_accounts,
                    "cost_center": cost_centers,
                    "qty": row["ItemQuantity"],
                    # "warehouse":row["Location"].strip() +" - DCL",
                    "warehouse": to_warehouse,
                    "InventoryStatus": row["InventoryStatus"],
                    "PaymentStatus": row["PaymentStatus"],
                    "OrderDate": row["OrderDate"]
                })
                print last_single_SI_items
                last_single_SI_dict = {"doctype": "Purchase Order",
                                       "title": current_customer,
                                       "supplier": current_customer,
                                       "posting_date": dt.date(),
                                       "schedule_date": dt.date(),  # TODO + 30 days
                                       "transaction_date": dt.date(),
                                       # "due_date": row["DueDate"],
                                       "due_date": dt.date(),
                                       "items": last_single_SI_items,
                                       # "docstatus": 1,
                                       "outstanding_amount": total_paid,
                                       "name": row["OrderNumber"],
                                       "OrderDate": dt,
                                       "inflow_remarks": row["OrderRemarks"],
                                       "currency": currency,
                                       "conversion_rate": conversion_rate,
                                       "inflow_file":file
                                       }

                if row["PaymentStatus"] == "Paid" and row["InventoryStatus"] == "Fulfilled":
                    last_single_paid_and_fulfilled_items.append({
                        # "item_code": installment.item,  # test
                        "description": row["ItemDescription"] or row["ItemName"],
                        "item_name": item_code1,
                        "item_code": item_code1,
                        # "rate": truncate(float(row["ItemSubtotal"]),2),
                        "rate": truncate(float(row["ItemUnitPrice"]), 2),
                        "conversion_factor": 1,
                        "uom": "Nos",
                        "expense_account": income_accounts,
                        "cost_center": cost_centers,
                        "qty": row["ItemQuantity"],
                        # "warehouse": row["Location"].strip() + " - DCL",
                        "warehouse": to_warehouse,
                        "InventoryStatus": row["InventoryStatus"],
                        "PaymentStatus": row["PaymentStatus"]
                    })

                if row["PaymentStatus"] == "Paid" and row["InventoryStatus"] != "Fulfilled":
                    last_single_paid_items.append({
                        # "item_code": installment.item,  # test
                        "description": row["ItemDescription"] or row["ItemName"],
                        "item_name": item_code1,
                        "item_code": item_code1,
                        # "rate": truncate(float(row["ItemSubtotal"]),2),
                        "rate": truncate(float(row["ItemUnitPrice"]), 2),
                        "conversion_factor": 1,
                        "uom": "Nos",
                        "expense_account": income_accounts,
                        "cost_center": cost_centers,
                        "qty": row["ItemQuantity"],
                        # "warehouse": row["Location"].strip() + " - DCL",
                        "warehouse": to_warehouse,
                        "InventoryStatus": row["InventoryStatus"],
                        "PaymentStatus": row["PaymentStatus"]
                    })

                if row["PaymentStatus"] != "Paid" and row["InventoryStatus"] == "Fulfilled":
                    last_single_fulfilled_items.append({
                        "description": row["ItemDescription"] or row["ItemName"],
                        "item_name": item_code1,
                        "item_code": item_code1,
                        "rate": truncate(float(row["ItemUnitPrice"]), 2),
                        "conversion_factor": 1,
                        "uom": "Nos",
                        "expense_account": income_accounts,
                        "cost_center": cost_centers,
                        "qty": row["ItemQuantity"],
                        # "warehouse": row["Location"].strip() + " - DCL",
                        "warehouse": to_warehouse,
                        "InventoryStatus": row["InventoryStatus"],
                        "PaymentStatus": row["PaymentStatus"]
                    })

                last_single_total_paid += float(row["ItemSubtotal"])


            SI_dict.update({"outstanding_amount":total_paid,
                            "inflow_file":file,
                            "per_received":100.0,
                            "per_billed":100.0
                            })

            print SI_dict["items"]
            SI = frappe.get_doc(SI_dict)
            # print SI_dict
            print("                     CURRENT:",current_order,SI_dict["po_status"])
            SI_created = SI.insert(ignore_permissions=True)
            SI_created.submit()
            """
            To Receive and Bill
            To Bill
            To Receive
            Completed
            """
            # print "                   PO Status: ",SI_dict["po_status"]
            # if SI_dict["po_status"] == "To Receive and Bill":
            #     print "To Receive and Bill"
            #     SI_created.db_set("per_received", 100, update_modified=False)
            #     SI_created.db_set("per_billed", 100, update_modified=False)
            # elif SI_dict["po_status"] == "To Receive":
            #     print "To Receive"
            #     SI_created.db_set("per_billed", 100, update_modified=False)
            # if SI_dict["po_status"] == "To Bill":
            #     print "To Bill"
            #     SI_created.db_set("per_received", 100, update_modified=False)


            # SI_created.status = SI_dict["po_status"]
            frappe.db.commit()
            #/home/jvfiel/frappe-v11/apps/erpnext/erpnext/buying/doctype/purchase_order/purchase_order.py
            from erpnext.buying.doctype.purchase_order.purchase_order import update_status


            #/home/jvfiel/frappe-v11/apps/frappe/frappe/model/rename_doc.py
            rename_doc("Purchase Order",SI_created.name,current_order,force=True)
            frappe.db.commit()

            # update_status(SI_dict["po_status"], current_order)
            # SI_created.set_status(update=True, status=SI_dict["po_status"])

            #self.db_set('status', self.status, update_modified = update_modified)
            # SI_created.db_set(fieldname='status',value=SI_dict['po_status'])
            # frappe.db.sql("""UPDATE `tabPurchase Order` SET status=%s WHERE name=%s""",(SI_dict["po_status"],current_order),debug=1)
            #self.db_set("per_received", flt(received_qty / total_qty) * 100, update_modified=False)
            # frappe.db.commit()

            print paid_and_fulfilled_items
            if paid_and_fulfilled_items:
                pi = make_purchase_invoice(current_order)
                if to_warehouse:
                    pi.update_stock = 1
                pi.is_paid = 1
                pi.items = []
                pi.posting_date = SI_dict['OrderDate'].date()
                pi.posting_time = str(SI_dict['OrderDate'].time())
                pi_total = 0.0
                if float(SI_dict["conversion_rate"]) != 0.0 and float(SI_dict["conversion_rate"]) != 1.0:
                    pi.currency = SI_dict["currency"]
                    pi.conversion_rate = float(SI_dict["conversion_rate"])
                elif float(SI_dict["conversion_rate"]) == 0.0 or float(SI_dict["conversion_rate"]) == 1.0:
                    pi.currency = "NGN"
                    pi.conversion_rate = None
                zeros = []
                for item in paid_and_fulfilled_items:
                    # if float(item["rate"]) < 0:
                    #     zeros.append(item)
                    # else:
                    nl = pi.append('items', {})
                    nl.description = item["description"]
                    nl.item_name = item["item_name"]
                    nl.item_code = item["item_name"]
                    nl.rate = float(item["rate"])
                    # nl.base_rate = float(item["rate"])
                    nl.conversion_factor = item["conversion_factor"]
                    nl.uom = item["uom"]
                    nl.expense_account = item["expense_account"]
                    nl.cost_center = item["cost_center"]
                    nl.qty = float(item["qty"])
                    nl.warehouse = item["warehouse"]
                    nl.purchase_order = current_order
                    pi_total += float(nl.rate) * float(nl.qty)
                    print(nl.rate)
                # if pi.items:
                pi.set_posting_time = 1
                pi.cash_bank_account = "Access Bank - DCL"
                pi.taxes_and_charges = ""
                pi.taxes = []
                pi.inflow_file = file
                print "             ", paid_and_fulfilled_items
                print "             Paid and Fulfilled PI Total", pi_total,current_order,pi.currency
                # print "             ", pi.as_dict()["items"]
                if pi_total:
                    pi.mode_of_payment = "Cash"
                    # if pi.conversion_rate:
                    # print "<<<<",pi.grand_total,">>>>"
                    # print "<<<<",pi.conversion_rate,">>>>"
                    # print "<<<<",pi.grand_total * pi.conversion_rate,">>>>"
                    pi.paid_amount = pi.grand_total
                    pi.base_paid_amount = pi.outstanding_amount
                    pi.insert()
                    pi.save()
                    frappe.db.commit()
                    pi.submit()
                    frappe.db.commit()
                else:
                    for item in zeros:
                        make_stock_entry(item_code=item["item_code"], qty=item['qty'],
                                         to_warehouse=item["warehouse"],
                                         valuation_rate=1, remarks="This is affected by data import. " + file,
                                         posting_date=pi.posting_date,
                                         posting_time=pi.posting_time,
                                         set_posting_time=1, inflow_file=file)
                        frappe.db.commit()
                        print "Stock entry created."

            if paid_items:
                pi = make_purchase_invoice(current_order)
                # pi.update_stock = 1
                pi.is_paid = 1
                pi.items = []
                pi.posting_date = SI_dict['OrderDate'].date()
                pi.posting_time = str(SI_dict['OrderDate'].time())
                pi_total = 0.0
                if float(SI_dict["conversion_rate"]) != 0.0 and float(SI_dict["conversion_rate"]) != 1.0:
                    pi.currency = SI_dict["currency"]
                    pi.conversion_rate = float(SI_dict["conversion_rate"])
                elif float(SI_dict["conversion_rate"]) == 0.0 or float(SI_dict["conversion_rate"]) == 1.0:
                    pi.currency = "NGN"
                    pi.conversion_rate = None
                zeros = []
                for item in paid_items:
                    nl = pi.append('items', {})
                    nl.description = item["description"]
                    nl.item_name = item["item_name"]
                    nl.item_code = item["item_name"]
                    nl.rate = float(item["rate"])
                    nl.conversion_factor = item["conversion_factor"]
                    nl.uom = item["uom"]
                    nl.expense_account = item["expense_account"]
                    nl.cost_center = item["cost_center"]
                    nl.qty = float(item["qty"])
                    nl.warehouse = item["warehouse"]
                    nl.purchase_order = current_order

                    pi_total += float(nl.rate) * float(nl.qty)
                # if pi.items:
                pi.set_posting_time = 1
                pi.cash_bank_account = "Access Bank - DCL"
                pi.taxes_and_charges = ""
                pi.taxes = []
                pi.inflow_file = file
                print "             Paid Items:", paid_items
                print "             Paid Items Only PI Total", pi_total,current_order,pi.currency
                # print "             ", pi.as_dict()["items"]
                if pi_total:
                    pi.mode_of_payment = "Cash"
                    pi.insert()
                    frappe.db.commit()
                    if pi.currency != "NGN":
                        pi.paid_amount = pi.grand_total
                        pi.base_paid_amount = pi.outstanding_amount
                        pi.save()
                        frappe.db.commit()
                    pi.submit()
                    frappe.db.commit()
                else:
                    pass


            if fulfilled_items:
                pi = make_purchase_invoice(current_order)
                if to_warehouse:
                    pi.update_stock = 1
                # pi.is_paid = 1
                pi.items = []
                pi.posting_date = SI_dict['OrderDate'].date()
                pi.posting_time = str(SI_dict['OrderDate'].time())
                pi_total = 0.0
                if float(SI_dict["conversion_rate"]) != 0.0 and float(
                        SI_dict["conversion_rate"]) != 1.0:
                    pi.currency = SI_dict["currency"]
                    pi.conversion_rate = float(SI_dict["conversion_rate"])
                elif float(SI_dict["conversion_rate"]) == 0.0 or float(
                        SI_dict["conversion_rate"]) == 1.0:
                    pi.currency = "NGN"
                    pi.conversion_rate = None
                zeros = []
                for item in fulfilled_items:
                    nl = pi.append('items', {})
                    nl.description = item["description"]
                    nl.item_name = item["item_name"]
                    nl.item_code = item["item_name"]
                    nl.rate = float(item["rate"])
                    nl.conversion_factor = item["conversion_factor"]
                    nl.uom = item["uom"]
                    nl.expense_account = item["expense_account"]
                    nl.cost_center = item["cost_center"]
                    nl.qty = float(item["qty"])
                    nl.received_qty = float(item["qty"])
                    nl.warehouse = item["warehouse"]
                    nl.purchase_order = current_order

                    pi_total += abs(float(nl.rate) * float(nl.qty))
                    # print nl.rate
                # if pi.items:
                pi.set_posting_time = 1
                pi.cash_bank_account = "Access Bank - DCL"
                pi.taxes_and_charges = ""
                pi.taxes = []
                pi.inflow_file = file
                print "             ", fulfilled_items
                print "             Fulfilled Items Only PI Total", pi_total, current_order, pi.currency
                print "             conversion rate", pi.conversion_rate
                if pi_total:
                    pi.mode_of_payment = "Cash"
                    pi.insert()
                    frappe.db.commit()
                    if pi.currency != "NGN":
                        # pi.paid_amount = pi.grand_total
                        # pi.base_paid_amount = pi.outstanding_amount
                        pi.rounding_adjustment = 0.0
                        pi.disable_rounded_total = 1
                        pi.save()
                        frappe.db.commit()
                    pi.submit()
                    frappe.db.commit()
                else:
                    pass




            current_customer = row["Vendor"].strip()
            current_order = row["OrderNumber"]
            dt = parser.parse(row["OrderDate"])
            SI_items = []

            currency = ""
            conversion_rate = 0.0
            if float(row["ExchangeRate"]) != 0.0 and float(row["ExchangeRate"]) != 1.0:
                currency = row["CurrencyCode"]
                conversion_rate = float(row["ExchangeRate"])
            elif float(row["ExchangeRate"]) == 0.0 or float(row["ExchangeRate"]) == 1.0:
                currency = "NGN"
                conversion_rate = 0.0

            po_status = ""
            if row["InventoryStatus"] == "Fulfilled" and row["PaymentStatus"] == "Paid":
                po_status = "Completed"
            elif row["InventoryStatus"] == "Unfulfilled" and row["PaymentStatus"] == "Paid":
                po_status = "To Receive"
            elif row["InventoryStatus"] == "Fulfilled" and row["PaymentStatus"] == "Unpaid":
                po_status = "To Bill"
            SI_dict = {"doctype": "Purchase Order",
                       "title": current_customer,
                       "supplier": current_customer,
                       "posting_date": dt.date(),
                       "schedule_date": dt.date(),  # TODO + 30 days
                       "transaction_date": dt.date(),
                       # "due_date": row["DueDate"],
                       "po_status":po_status,
                       "due_date": dt.date(),
                       "items": SI_items,
                       # "docstatus": 1,
                       "outstanding_amount": total_paid,
                       "name": row["OrderNumber"],
                       "OrderDate":dt,
                       "inflow_remarks": row["OrderRemarks"],
                       "inflow_file": file,
                       "currency": currency,
                       "conversion_rate": conversion_rate
                       }
            paid_items = []
            fulfilled_items = []
            paid_and_fulfilled_items = []


        # else:
        item_code1 = row["ItemName"].strip()
        # if row[
        #     "ItemName"] == "Kerosene stove, four burner pressure type for use with 39L autoclave / steriliser.\nSupplied specifically without top plate (ring) for use only with the autoclave / steam sterilizer.":
        if "Kerosene stove, four burner pressure type for use with 39L autoclave / steriliser." in item_code1:
            item_code1 = "Kerosene Stove"
        SI_item = {
            # "item_code": installment.item,  # test
            "description": row["ItemDescription"].strip() or row["ItemName"],
            "item_name": item_code1,
            "item_code": item_code1,
            # "warehouse": row["Location"].strip() +" - DCL",
            "warehouse": to_warehouse,
            "rate": float(row["ItemUnitPrice"]),
            "conversion_factor":1,
            "uom":"Nos",
            "expense_account": income_accounts,
            "cost_center": cost_centers,
            "qty": float(row["ItemQuantity"]),
            "received_qty": float(row["ItemQuantity"]),
            "InventoryStatus": row["InventoryStatus"],
            "PaymentStatus": row["PaymentStatus"],
            "OrderDate":row["OrderDate"]
        }
        SI_items.append(SI_item)

        if row["PaymentStatus"] == "Paid" and row["InventoryStatus"] == "Fulfilled":
            paid_and_fulfilled_items.append({
                # "item_code": installment.item,  # test
                "description": row["ItemDescription"] or row["ItemName"],
                "item_name": item_code1,
                "item_code": item_code1,
                # "rate": truncate(float(row["ItemSubtotal"]),2),
                "rate": truncate(float(row["ItemUnitPrice"]), 2),
                "conversion_factor": 1,
                "uom": "Nos",
                "expense_account": income_accounts,
                "cost_center": cost_centers,
                "qty": row["ItemQuantity"],
                # "warehouse": row["Location"].strip() + " - DCL",
                "warehouse": to_warehouse,
                "InventoryStatus": row["InventoryStatus"],
                "PaymentStatus": row["PaymentStatus"]
            })

        if row["PaymentStatus"] == "Paid" and row["InventoryStatus"] != "Fulfilled":
            paid_items.append({
                # "item_code": installment.item,  # test
                "description": row["ItemDescription"] or row["ItemName"],
                "item_name": item_code1,
                "item_code": item_code1,
                # "rate": truncate(float(row["ItemSubtotal"]),2),
                "rate": truncate(float(row["ItemUnitPrice"]), 2),
                "conversion_factor": 1,
                "uom": "Nos",
                "expense_account": income_accounts,
                "cost_center": cost_centers,
                "qty": row["ItemQuantity"],
                # "warehouse": row["Location"].strip() + " - DCL",
                "warehouse": to_warehouse,
                "InventoryStatus": row["InventoryStatus"],
                "PaymentStatus": row["PaymentStatus"]
            })

        if row["PaymentStatus"] != "Paid" and row["InventoryStatus"] == "Fulfilled":
            fulfilled_items.append({
                "description": row["ItemDescription"] or row["ItemName"],
                "item_name": item_code1,
                "item_code": item_code1,
                "rate": truncate(float(row["ItemUnitPrice"]), 2),
                "conversion_factor": 1,
                "uom": "Nos",
                "expense_account": income_accounts,
                "cost_center": cost_centers,
                "qty": row["ItemQuantity"],
                # "warehouse": row["Location"].strip() + " - DCL",
                "warehouse": to_warehouse,
                "InventoryStatus": row["InventoryStatus"],
                "PaymentStatus": row["PaymentStatus"]
            })

        total_paid +=float(row["ItemSubtotal"])



    if last_single_SI_dict != {}:

        print "* END *", current_order
        print last_single_SI_dict["items"]
        SI = frappe.get_doc(last_single_SI_dict)
        # print SI_dict
        SI_created = SI.insert(ignore_permissions=True)
        frappe.db.commit()
        SI_created.submit()
        frappe.db.commit()
        rename_doc("Purchase Order", SI_created.name, current_order, force=True)
        frappe.db.commit()
        if last_single_paid_and_fulfilled_items:
            pi = make_purchase_invoice(current_order)
            pi.update_stock = 1
            pi.is_paid = 1
            pi.items = []
            pi.posting_date = SI_dict['OrderDate'].date()
            pi.posting_time = str(SI_dict['OrderDate'].time())
            pi_total = 0.0
            if float(last_single_SI_dict["conversion_rate"]) != 0.0 and float(last_single_SI_dict["conversion_rate"]) != 1.0:
                pi.currency = SI_dict["currency"]
                pi.conversion_rate = float(SI_dict["conversion_rate"])
            elif float(last_single_SI_dict["conversion_rate"]) == 0.0 or float(last_single_SI_dict["conversion_rate"]) == 1.0:
                pi.currency = "NGN"
                pi.conversion_rate = None
            zeros = []
            for item in last_single_paid_and_fulfilled_items:
                # if float(item["rate"]) < 0:
                #     zeros.append(item)
                # else:
                nl = pi.append('items', {})
                nl.description = item["description"]
                nl.item_name = item["item_name"]
                nl.item_code = item["item_name"]
                nl.rate = float(item["rate"])
                # nl.base_rate = float(item["rate"])
                nl.conversion_factor = item["conversion_factor"]
                nl.uom = item["uom"]
                nl.expense_account = item["expense_account"]
                nl.cost_center = item["cost_center"]
                nl.qty = float(item["qty"])
                nl.warehouse = item["warehouse"]
                nl.purchase_order = current_order
                pi_total += float(nl.rate) * float(nl.qty)
            # if pi.items:
            pi.set_posting_time = 1
            pi.cash_bank_account = "Access Bank - DCL"
            pi.taxes_and_charges = ""
            pi.taxes = []
            pi.inflow_file = file
            # print "             ", paid_and_fulfilled_items
            print "             Paid and Fulfilled PI Total", pi_total, current_order, pi.currency
            # print "             ", pi.as_dict()["items"]
            if pi_total:
                pi.mode_of_payment = "Cash"
                # if pi.conversion_rate:
                # print "<<<<",pi.grand_total,">>>>"
                # print "<<<<",pi.conversion_rate,">>>>"
                # print "<<<<",pi.grand_total * pi.conversion_rate,">>>>"
                pi.paid_amount = pi.grand_total
                pi.base_paid_amount = pi.outstanding_amount
                pi.insert()
                pi.save()
                frappe.db.commit()
                pi.submit()
                frappe.db.commit()
            else:
                for item in zeros:
                    make_stock_entry(item_code=item["item_code"], qty=item['qty'],
                                     to_warehouse=item["warehouse"],
                                     valuation_rate=1, remarks="This is affected by data import. " + file,
                                     posting_date=pi.posting_date,
                                     posting_time=pi.posting_time,
                                     set_posting_time=1, inflow_file=file)
                    frappe.db.commit()
                    print "Stock entry created."

        if last_single_paid_items:
            pi = make_purchase_invoice(current_order)
            # pi.update_stock = 1
            pi.is_paid = 1
            pi.items = []
            pi.posting_date = last_single_SI_dict['OrderDate'].date()
            pi.posting_time = str(last_single_SI_dict['OrderDate'].time())
            pi_total = 0.0
            if float(last_single_SI_dict["conversion_rate"]) != 0.0 and float(last_single_SI_dict["conversion_rate"]) != 1.0:
                pi.currency = last_single_SI_dict["currency"]
                pi.conversion_rate = float(last_single_SI_dict["conversion_rate"])
            elif float(last_single_SI_dict["conversion_rate"]) == 0.0 or float(last_single_SI_dict["conversion_rate"]) == 1.0:
                pi.currency = "NGN"
                pi.conversion_rate = None
            zeros = []
            for item in last_single_paid_items:
                nl = pi.append('items', {})
                nl.description = item["description"]
                nl.item_name = item["item_name"]
                nl.item_code = item["item_name"]
                nl.rate = float(item["rate"])
                nl.conversion_factor = item["conversion_factor"]
                nl.uom = item["uom"]
                nl.expense_account = item["expense_account"]
                nl.cost_center = item["cost_center"]
                nl.qty = float(item["qty"])
                nl.warehouse = item["warehouse"]
                nl.purchase_order = current_order

                pi_total += float(nl.rate) * float(nl.qty)
            # if pi.items:
            pi.set_posting_time = 1
            pi.cash_bank_account = "Access Bank - DCL"
            pi.taxes_and_charges = ""
            pi.taxes = []
            pi.inflow_file = file
            # print "             ", paid_items
            print "             Paid Items Only PI Total", pi_total, current_order, pi.currency
            # print "             ", pi.as_dict()["items"]
            if pi_total:
                pi.mode_of_payment = "Cash"
                pi.insert()
                frappe.db.commit()
                if pi.currency != "NGN":
                    pi.paid_amount = pi.grand_total
                    pi.base_paid_amount = pi.outstanding_amount
                    pi.save()
                    frappe.db.commit()
                pi.submit()
                frappe.db.commit()
            else:
                pass

        if last_single_fulfilled_items:
            pi = make_purchase_invoice(current_order)
            pi.update_stock = 1
            # pi.is_paid = 1
            pi.items = []
            pi.posting_date = last_single_SI_dict['OrderDate'].date()
            pi.posting_time = str(last_single_SI_dict['OrderDate'].time())
            pi_total = 0.0
            if float(last_single_SI_dict["conversion_rate"]) != 0.0 and float(
                    last_single_SI_dict["conversion_rate"]) != 1.0:
                pi.currency = last_single_SI_dict["currency"]
                pi.conversion_rate = float(last_single_SI_dict["conversion_rate"])
            elif float(last_single_SI_dict["conversion_rate"]) == 0.0 or float(
                    last_single_SI_dict["conversion_rate"]) == 1.0:
                pi.currency = "NGN"
                pi.conversion_rate = None
            zeros = []
            for item in last_single_fulfilled_items:
                nl = pi.append('items', {})
                nl.description = item["description"]
                nl.item_name = item["item_name"]
                nl.item_code = item["item_name"]
                nl.rate = float(item["rate"])
                nl.conversion_factor = item["conversion_factor"]
                nl.uom = item["uom"]
                nl.expense_account = item["expense_account"]
                nl.cost_center = item["cost_center"]
                nl.qty = float(item["qty"])
                nl.warehouse = item["warehouse"]
                nl.purchase_order = current_order

                pi_total += float(nl.rate) * float(nl.qty)
            # if pi.items:
            pi.set_posting_time = 1
            pi.cash_bank_account = "Access Bank - DCL"
            pi.taxes_and_charges = ""
            pi.taxes = []
            pi.inflow_file = file
            # print "             ", paid_items
            print "             Paid Items Only PI Total", pi_total, current_order, pi.currency
            # print "             ", pi.as_dict()["items"]
            if pi_total:
                pi.mode_of_payment = "Cash"
                pi.insert()
                frappe.db.commit()
                if pi.currency != "NGN":
                    pi.paid_amount = pi.grand_total
                    pi.base_paid_amount = pi.outstanding_amount
                    pi.save()
                    frappe.db.commit()
                pi.submit()
                frappe.db.commit()
            else:
                pass

    None