Exemplo n.º 1
0
def create_bill_of_lading(transaction_executor,sender_id, reciever_id,container_id, sea_carrier_id,export_port_id,import_port_id):
    bolno =  get_index_number(transaction_executor,Constants.BILL_OF_LADING_TABLE_NAME,Constants.BILL_OF_LADING_INDEX_NAME)
    export_port_name = get_value_from_documentid(transaction_executor,Constants.SCENTITY_TABLE_NAME,export_port_id,"ScEntityName")
    import_port_name = get_value_from_documentid(transaction_executor,Constants.SCENTITY_TABLE_NAME,import_port_id,"ScEntityName")


    bill_of_lading = {
        "BillOfLadingNumber" : bolno,
        "CarrierId":sea_carrier_id,
        "Container_id":container_id,
        "SeaCarrierApproval":{
            "isApproved":False,
            "ApproverId":""
        },
        "RecieverApproval":{
            "isApproved": False,
            "ApproverId":""
        },
        "SenderScEntityId":sender_id,
        "RecieverScEntityId":reciever_id, # If the same carrier is transporting the container then reciever Id will be carrier id
        "isDelivered":False,
        "WarehouseId":"",
        "ExportPortId":export_port_id,
        "ExportPortName":export_port_name[0],
        "ImportPortId":import_port_id,
        "ImportPortName":import_port_name[0]
    }
    
    bill_of_lading_id = insert_documents(transaction_executor,Constants.BILL_OF_LADING_TABLE_NAME,convert_object_to_ion(bill_of_lading))
    return bill_of_lading_id
Exemplo n.º 2
0
def threshhold_crossed(transaction_executor, iot_id, iot_data):
    container_id = get_value_from_documentid(transaction_executor,Constants.IOT_TABLE_NAME,iot_id,"ContainerId")
    purchase_order_id = get_value_from_documentid(transaction_executor, Constants.CONTAINER_TABLE_NAME,container_id[0],"PurchaseOrderIds") 
    product_id = get_value_from_documentid(transaction_executor, Constants.PURCHASE_ORDER_TABLE_NAME,purchase_order_id[0][-1],"ProductId")
    print(product_id)
    iot_type = get_value_from_documentid(transaction_executor,Constants.IOT_TABLE_NAME,iot_id,"IoTType")
    if iot_type == [1]:
        temp_data = iot_data["Temperature"]
        low_thresh_temp = get_storage_data(transaction_executor,product_id[0],'LowThreshTemp')
        high_thresh_temp = get_storage_data(transaction_executor,product_id[0],'HighThreshTemp')

        if high_thresh_temp <= temp_data or temp_data <= low_thresh_temp:
            logger.info("Temp threshold crossed!!")
            return True
        else:
            logger.info("Temperature is good")
            return False
    elif iot_type == [2]:
        humidity_data = iot_data["Humidity"]
        high_thresh_humdity = get_storage_data(transaction_executor,product_id[0],"HighThreshHumidity")
        if humidity_data >= high_thresh_humdity:
            logger.info("Humidity Threshold crossed!")
            return True
        else:
            logger.info("Humdity ok")
            return False
Exemplo n.º 3
0
def create_airway_bill(transaction_executor,sender_id, reciever_id,container_id, air_carrier_id,export_airport_id,import_airport_id):
    awbillno = get_index_number(transaction_executor,Constants.AIRWAY_BILL_TABLE_NAME,Constants.AIRWAY_BILL_INDEX_NAME)
    export_airport_name = get_value_from_documentid(transaction_executor,Constants.SCENTITY_TABLE_NAME,export_airport_id,"ScEntityName")
    import_airport_name = get_value_from_documentid(transaction_executor,Constants.SCENTITY_TABLE_NAME,import_airport_id,"ScEntityName")
    airway_bill = {
        "AirwayBillNumber" : awbillno,
        "CarrierId":air_carrier_id,
        "ContainerId":container_id,
        "AirCarrierApproval":{
            "isApproved":False,
            "ApproverId":""
        },
        "RecieverApproval":{
            "isApproved": False,
            "ApproverId":""
        },
        "SenderScEntityId":sender_id,
        "RecieverScEntityId":reciever_id,
        "isDelivered":False,
        "WarehouseId":"",
        "ExportAirportId":export_airport_id,
        "ExportAirportName":export_airport_name[0],
        "ImportAirportId":import_airport_id,
        "ImportAirportName":import_airport_name[0]
    }
    
    airway_bill_id = insert_documents(transaction_executor,Constants.AIRWAY_BILL_TABLE_NAME,convert_object_to_ion(airway_bill))
    return airway_bill_id
Exemplo n.º 4
0
def approve_joining_request(transaction_executor, request_id,person_id):
    
    # check if request agrees with the id
    if request_exists(transaction_executor, request_id):
        # approve the request'
        # logger.info(" Request exists.")
        sc_entity_id = get_value_from_documentid(transaction_executor,Constants.JOINING_REQUEST_TABLE_NAME,request_id,"ScEntityId")
        actual_scentity_id = get_scentityid_from_personid(transaction_executor,person_id)
        if sc_entity_id[0] == actual_scentity_id:
            # logger.info("Authorized!")
            if get_value_from_documentid(transaction_executor, Constants.JOINING_REQUEST_TABLE_NAME, request_id, 'isAccepted') == [1]: 
                raise Exception("Request Already accepted")
                
            else:   
                update_statement = " UPDATE JoiningRequest AS j BY id SET j.isAccepted = true WHERE id = ?"
                transaction_executor.execute_statement(update_statement, request_id)
                
                person_id = get_value_from_documentid(transaction_executor, Constants.JOINING_REQUEST_TABLE_NAME, request_id, 'SenderPersonId')
                person_id = person_id[0]
                scentity_id = get_value_from_documentid(transaction_executor, Constants.JOINING_REQUEST_TABLE_NAME, request_id, 'ScEntityId')
                join_person_to_company(transaction_executor, scentity_id[0], person_id)
                # logger.info("Request : {} Accepted".format(request_id))
                return_statement = " ================================== P E R S O N =========== A D D E D ==============================="
                return return_statement
        else:
            raise Exception("Person not authorized")    
    else:
        raise Exception("Request doesn't exist.")
Exemplo n.º 5
0
def enough_inventory_registered_for_order(transaction_executor,
                                          products_per_case, purchase_order_id,
                                          batch_table_name):
    container_order_quantity = get_value_from_documentid(
        transaction_executor, Constants.PURCHASE_ORDER_TABLE_NAME,
        purchase_order_id, "OrderQuantity")
    container_order_quantity = int(container_order_quantity[0])
    product_units_ordered = container_order_quantity * Constants.PALLETS_PER_CONTAINER * Constants.CASES_PER_PALLETE * int(
        products_per_case)

    statement = 'SELECT SUM(b.UnitsRemaining) as invrem FROM {} as b WHERE b.UnitsRemaining > 0'.format(
        batch_table_name)

    cursor = transaction_executor.execute_statement(statement)
    inventory_remaining = list(map(lambda x: x.get('invrem'), cursor))
    inventory_remaining = int(
        dumps(inventory_remaining[0],
              binary=False,
              indent='  ',
              omit_version_marker=True))

    if inventory_remaining >= product_units_ordered:
        # logger.info(" Enough inventory to pack the order: {}!".format(inventory_remaining))
        return product_units_ordered
    else:
        # logger.info("Not enough inventory!")
        return False
Exemplo n.º 6
0
def create_certificate_of_origin(transaction_executor, product_id):
    product_name = get_value_from_documentid(transaction_executor,
                                             Constants.PRODUCT_TABLE_NAME,
                                             product_id, "ProductName")
    product_hs_tarriff = get_value_from_documentid(
        transaction_executor, Constants.PRODUCT_TABLE_NAME, product_id,
        "ProductHSTarriffNumber")
    manufacturer_id = get_value_from_documentid(transaction_executor,
                                                Constants.PRODUCT_TABLE_NAME,
                                                product_id, "ManufacturerId")
    manufacturer_name = get_value_from_documentid(
        transaction_executor, Constants.SCENTITY_TABLE_NAME,
        manufacturer_id[0], "ScEntityName")

    certificate_of_origin = {
        'CertificateOfOriginNumber':
        get_index_number(transaction_executor,
                         Constants.CERTIFICATE_OF_ORIGIN_TABLE_NAME,
                         "CertificateOfOriginNumber"),
        'ProductName':
        product_name[0],
        'Productid':
        product_id,
        'ProductHSTarriffNumber':
        product_hs_tarriff[0],
        'ManufacturerId':
        manufacturer_id[0],
        'ManufacturerName':
        manufacturer_name[0],
        'ManufacturerLocation':
        get_scentity_contact(transaction_executor, manufacturer_id[0],
                             "Address")[0],
        'ExportApproval': {
            "ApproverId": "",
            "isApprovedByCustoms": False
        },
        'ImportApproval': {
            "ApproverId": "",
            "isApprovedByCustoms": False
        }
    }

    certificate_of_origin_id = insert_documents(
        transaction_executor, Constants.CERTIFICATE_OF_ORIGIN_TABLE_NAME,
        convert_object_to_ion(certificate_of_origin))
    # logger.info("Certificate of Origin Created successfully!")
    return certificate_of_origin_id
Exemplo n.º 7
0
def shipment_already_started(transaction_executor, purchase_order_id):
    container_ids = get_value_from_documentid(
        transaction_executor, Constants.PURCHASE_ORDER_TABLE_NAME,
        purchase_order_id, "HighestPackagingLevelIds")

    if len(container_ids[0]) > 0:
        # logger.info("Shipment already began. Following container ids were : {}".format(container_ids))
        return True
    else:
        return False
Exemplo n.º 8
0
def approve_import_customs(transaction_executor,conatiner_id,customs_person_id,warehouse_id):
    certificate_of_origin_id = get_value_from_documentid(transaction_executor,Constants.CONTAINER_TABLE_NAME,conatiner_id,"CertificateOfOriginId")
    packing_list_id = get_value_from_documentid(transaction_executor, Constants.CONTAINER_TABLE_NAME,conatiner_id,"PackingListId")
    export_custom_approved = (document_already_approved_by_customs(transaction_executor,"ExportApproval",Constants.CERTIFICATE_OF_ORIGIN_TABLE_NAME,certificate_of_origin_id[0]) and
    document_already_approved_by_customs(transaction_executor,"ExportApproval", Constants.PACKING_LIST_TABLE_NAME,packing_list_id[0]))  

    if export_custom_approved:
        import_custom_approved = (document_already_approved_by_customs(transaction_executor,"ImportApproval",Constants.CERTIFICATE_OF_ORIGIN_TABLE_NAME,certificate_of_origin_id[0]) and
        document_already_approved_by_customs(transaction_executor,"ImportApproval", Constants.PACKING_LIST_TABLE_NAME,packing_list_id[0]))

        # logger.info(import_custom_approved)
        if import_custom_approved:
            raise Exception("Already approved by import customs")
        else:
            # print("=============")
            custom_approval(transaction_executor,conatiner_id,"ImportApproval",customs_person_id)
            airway_bill_ids = get_value_from_documentid(transaction_executor,Constants.CONTAINER_TABLE_NAME,conatiner_id,"AirwayBillIds")
            update_document(transaction_executor,Constants.AIRWAY_BILL_TABLE_NAME,"isDelivered",airway_bill_ids[0][-1],True)
            update_document(transaction_executor,Constants.AIRWAY_BILL_TABLE_NAME,"WarehouseId",airway_bill_ids[0][-1],warehouse_id)
    else:
        raise Exception(" ======Not===Approved=======By==========Export=========")
Exemplo n.º 9
0
def update_approval_status(transaction_executor,request_id,status):
    request_type = get_value_from_documentid(transaction_executor,Constants.SUPERADMIN_REQUEST_TABLE_NAME,request_id,"RequestType")
    request_type = request_type[0]
    document_id = get_value_from_documentid(transaction_executor,Constants.SUPERADMIN_REQUEST_TABLE_NAME,request_id,"DocumentId")
    # logger.info(request_type)
    # logger.info(document_id)

    if request_type == 1:
        table_name = Constants.SCENTITY_TABLE_NAME

    else:
        table_name = Constants.PRODUCT_TABLE_NAME

    if status == "false":
       
        # delete this if statement if you want to keep person even if SCEntitiy is deleted
        if request_type == 1:
            person_ids = get_value_from_documentid(transaction_executor, table_name,document_id[0],'PersonIds')
            logger.info(person_ids)
            person_ids = person_ids[0]
            # logger.info('person_ids are :{}'.format(person_ids))
            delete_document(transaction_executor, Constants.PERSON_TABLE_NAME,person_ids)  
            # logger.info('Following documents were deleted : person id:{}'.format(person_ids))


        # id must be in list so request_id was converted to ['request_id']
        delete_document(transaction_executor,table_name,document_id)
        delete_document(transaction_executor,Constants.SUPERADMIN_REQUEST_TABLE_NAME, [request_id]) 
        # logger.info('Following documents were deleted :  product or scentity id: {} and request id:{}'.format(document_id,request_id))
        
    else:
        update_statement = "UPDATE {} AS j BY id SET j.isApprovedBySuperAdmin = true WHERE id = ?".format(table_name)
        document_id = document_id[0]
        cursor = transaction_executor.execute_statement(update_statement, document_id)
        try:
            next(cursor)
            # logger.info("Approval Status Updated!")
        except StopIteration:
            logger.exception("Status was not updated!")
Exemplo n.º 10
0
def person_authorized_to_create_product(transaction_executor, product_id,
                                        person_id):
    actual_scentity_id = get_scentityid_from_personid(transaction_executor,
                                                      person_id)
    ManufacturerId = get_value_from_documentid(transaction_executor,
                                               Constants.PRODUCT_TABLE_NAME,
                                               product_id, "ManufacturerId")
    # logger.info("actual_id: {} and manufactuter id : {}".format(actual_scentity_id,ManufacturerId))

    if actual_scentity_id == ManufacturerId[0]:
        # logger.info("Authorized!!")
        return True
    else:
        # logger.info("Ids not matched!")
        return False
Exemplo n.º 11
0
def assign_iot(transaction_executor, iot_id,container_id,person_id):
    # person_id must be super admin
    actual_sc_entity_id = get_scentityid_from_personid(transaction_executor,person_id)
    carrier_id = get_value_from_documentid(transaction_executor,Constants.CONTAINER_TABLE_NAME,container_id,"CarrierCompanyId")
    if actual_sc_entity_id == carrier_id[0]:
        if document_exist(transaction_executor,Constants.CONTAINER_TABLE_NAME,container_id):
            update_document(transaction_executor,Constants.IOT_TABLE_NAME,"ContainerId",iot_id,container_id)
            statement = "FROM {} AS s by id WHERE id = '{}' INSERT INTO s.IotIds VALUE ?".format(Constants.CONTAINER_TABLE_NAME,container_id)
            # print(statement)
            cursor = transaction_executor.execute_statement(statement,iot_id) 
            try:
                next(cursor)
                logger.info(" ========== I o T ========= A S S I G N E D ============")
            except:
                raise Exception("Problem in Iot assignment")
        else:
            raise Exception("Container not found")
    else:
        raise Exception("Not authorized!")
Exemplo n.º 12
0
def create_purchase_order_input(transaction_executor, purchase_order_id,
                                actual_sc_entity_id):
    product_id = get_value_from_documentid(transaction_executor,
                                           Constants.PURCHASE_ORDER_TABLE_NAME,
                                           purchase_order_id, "ProductId")
    # number of container if order type is 1 and number of dosage if order type is 2
    order_quantity = get_value_from_documentid(
        transaction_executor, Constants.PURCHASE_ORDER_TABLE_NAME,
        purchase_order_id, "OrderQuantity")

    order_type = get_value_from_documentid(transaction_executor,
                                           Constants.PURCHASE_ORDER_TABLE_NAME,
                                           purchase_order_id, "OrderType")
    products_per_container = get_value_from_documentid(
        transaction_executor, Constants.PRODUCT_TABLE_NAME, product_id[0],
        "ProductsPerContainer")

    if order_type[0] == "1":
        product_price = get_value_from_documentid(transaction_executor,
                                                  Constants.PRODUCT_TABLE_NAME,
                                                  product_id[0],
                                                  "ProductPrice")
    elif order_type[0] == "2":
        inventory_table = inventory_table_already_exist(
            transaction_executor, actual_sc_entity_id)
        product_id = get_value_from_documentid(
            transaction_executor, Constants.PURCHASE_ORDER_TABLE_NAME,
            purchase_order_id, "ProductId")
        inventory_id = next(
            get_document_ids(transaction_executor, inventory_table[0],
                             "ProductId", product_id[0]))
        product_price = get_value_from_documentid(transaction_executor,
                                                  inventory_table[0],
                                                  inventory_id, "ProductPrice")

    purchase_order_input = {
        "ProductId":
        product_id[0],
        "OrderQuantity":
        order_quantity[0],
        "OrderValue":
        order_quantity[0] * product_price[0] * products_per_container[0]
    }
    # logger.info(purchase_order_input)
    return purchase_order_input
Exemplo n.º 13
0
def create_packing_list(transaction_executor, products_per_container,
                        product_code, palleteIds):
    container_case_ids = []
    # print("pallete ids are : {}".format(palleteIds))
    for palleteId in palleteIds:
        pallete_case_ids = get_value_from_documentid(
            transaction_executor, Constants.PALLETE_TABLE_NAME, palleteId,
            "CaseIds")
        container_case_ids.append(pallete_case_ids[0])

    packing_list = {
        "PackingListNumber":
        get_index_number(transaction_executor,
                         Constants.PACKING_LIST_TABLE_NAME,
                         "PackingListNumber"),
        "NumberOfPalletes":
        Constants.PALLETS_PER_CONTAINER,
        "PalleteIds":
        palleteIds,
        "NumberofCases":
        Constants.PALLETS_PER_CONTAINER * Constants.CASES_PER_PALLETE,
        "CasesIds":
        container_case_ids,
        "ProductCode":
        product_code[0],
        "ProductQuantity":
        products_per_container,
        "ExportApproval": {
            "ApproverId": "",
            "isApprovedByCustoms": False
        },
        'ImportApproval': {
            "ApproverId": "",
            "isApprovedByCustoms": False
        }
    }

    packing_list_id = insert_documents(transaction_executor,
                                       Constants.PACKING_LIST_TABLE_NAME,
                                       packing_list)
    return packing_list_id[0]
Exemplo n.º 14
0
def create_batch(transaction_executor, person_id, product_id, batch):

    ##check if the ProductCode exists
    if product_exists(transaction_executor, product_id):
        ##check if the product is approved by superadmin
        if get_value_from_documentid(transaction_executor,
                                     Constants.PRODUCT_TABLE_NAME, product_id,
                                     "isApprovedBySuperAdmin"):
            ##check if the person_id is authorized to create the product
            if person_authorized_to_create_product(transaction_executor,
                                                   product_id, person_id):
                generate_inventory(transaction_executor, product_id, batch)
                logger.info(
                    " ================================== B A T C H =========== R E G I S T E R E D  ==============================="
                )
            else:
                raise Exception("You don't have authority for this product!")
        else:
            raise Exception("Wait for product to be approved by SuperAdmin.")
    else:
        raise Exception("Trouble finding product.")
Exemplo n.º 15
0
def check_container_safe(transaction_executor, iot_id, iot_data):
    if document_exist(transaction_executor,Constants.IOT_TABLE_NAME,iot_id):
        logger.info("document_exist!")
        container_id = get_value_from_documentid(transaction_executor,Constants.IOT_TABLE_NAME,iot_id,"ContainerId")

        if threshhold_crossed(transaction_executor,iot_id,iot_data):
            update_document(transaction_executor,Constants.CONTAINER_TABLE_NAME, "ContainerSafety.isContainerSafeForDelivery",container_id[0],False)
            update_document(transaction_executor,Constants.CONTAINER_TABLE_NAME, "ContainerSafety.LastCheckedAt",container_id[0],iot_data["TimeStamp"])
            logger.info("++++++++++ ===== C O N T A I N E R ===== U N S A F E ======= +++++++++")
            ## mark container unsafe
        else:
            if isContainerSafe(transaction_executor,container_id[0]):
                logger.info("No problem detected!")
                update_document(transaction_executor,Constants.CONTAINER_TABLE_NAME, "ContainerSafety.LastCheckedAt",container_id[0],iot_data["TimeStamp"])
            else:
                logger.info("ALARM!!! CONTAINER WAS ALREADY MARKED UNSAFE!!")
            ## check if the container is safe 
            # mark container safe
            # change the updated time
    else:
        logger.info("IoT with id : {} doesn't exist.".format(iot_id))
Exemplo n.º 16
0
def update_current_product_inventory(transaction_executor,
                                     inventory_table_name, product_id,
                                     product_instances, case_ids, pallete_ids,
                                     container_ids,
                                     delivered_product_quantity):
    inventory_id = next(
        get_document_ids(transaction_executor, inventory_table_name,
                         "ProductId", product_id))
    insert_value_in_inventory_table(transaction_executor, inventory_table_name,
                                    "CaseIds", inventory_id, case_ids)
    insert_value_in_inventory_table(transaction_executor, inventory_table_name,
                                    "PalleteIds", inventory_id, pallete_ids)
    insert_value_in_inventory_table(transaction_executor, inventory_table_name,
                                    "ContainerIds", inventory_id,
                                    container_ids)
    current_inventory = get_value_from_documentid(transaction_executor,
                                                  inventory_table_name,
                                                  inventory_id,
                                                  "CurrentInventory")

    updated_inventory = int(current_inventory[0]) + delivered_product_quantity
    update_document(transaction_executor, inventory_table_name,
                    "CurrentInventory", inventory_id, updated_inventory)
Exemplo n.º 17
0
def pick_up_order(transaction_executor,pick_up_request_id,truck_carrier_person_id, freight_carrier_id, export_location_id,import_location_id):
    if document_exist(transaction_executor,Constants.PICK_UP_REQUESTS_TABLE,pick_up_request_id):
        update_document(transaction_executor,Constants.PICK_UP_REQUESTS_TABLE,"isAccepted",pick_up_request_id,True)
        purchase_order_id = get_value_from_documentid(transaction_executor,Constants.PICK_UP_REQUESTS_TABLE, pick_up_request_id, "PurchaseOrderId")
        purchase_order_id = purchase_order_id[0]
        container_ids = get_value_from_documentid(transaction_executor,Constants.PURCHASE_ORDER_TABLE_NAME,purchase_order_id,"HighestPackagingLevelIds")
        carrier_company_id = get_value_from_documentid(transaction_executor,Constants.CONTAINER_TABLE_NAME,container_ids[0][0],"CarrierCompanyId")

        actual_sc_entity_id = get_scentityid_from_personid(transaction_executor,truck_carrier_person_id)

        if carrier_company_id[0]== actual_sc_entity_id:

            location_ids = [export_location_id,import_location_id]
            scentity_type_code = list(map(lambda x: get_value_from_documentid(transaction_executor,Constants.SCENTITY_TABLE_NAME,x,"ScEntityTypeCode"),location_ids))

            # print(scentity_type_code)
            if ["3"] not in scentity_type_code[0] and ["4"] not in scentity_type_code[0] and scentity_type_code[0][0] != scentity_type_code[1][0]:
                raise Exception("import and export locations  can only be airports or sea ports")
            else:
                # logger.info("Authorized!")

                if get_document_superadmin_approval_status(transaction_executor,Constants.SCENTITY_TABLE_NAME,freight_carrier_id):
                    product_id = get_value_from_documentid(transaction_executor,Constants.PURCHASE_ORDER_TABLE_NAME,purchase_order_id,"ProductId")
                    product_id = product_id[0]
                    manufacturer_id = get_value_from_documentid(transaction_executor,Constants.PRODUCT_TABLE_NAME,product_id,"ManufacturerId")
                    manufacturer_name = get_value_from_documentid(transaction_executor,Constants.SCENTITY_TABLE_NAME,manufacturer_id[0],"ScEntityName")
                    pick_up_location = get_scentity_contact(transaction_executor,manufacturer_id[0],"Address")
                    delivery_location = get_scentity_contact(transaction_executor,export_location_id,"Address")
                    # logger.info("Pickup location is : {}".format(pick_up_location))
                    airway_bill_ids = []
                    bill_of_lading_ids = []
                    lorry_reciept_ids = []
                    for container_id in container_ids[0]:
                        isPicked = get_value_from_documentid(transaction_executor,Constants.CONTAINER_TABLE_NAME,container_id,"isPicked")
                        if isPicked[0] == 0:
                            lorry_reciept_id = create_lorry_reciept(transaction_executor,actual_sc_entity_id,truck_carrier_person_id,pick_up_location[0],delivery_location[0],manufacturer_id[0],manufacturer_name[0],True)
                            lorry_reciept_ids.append(lorry_reciept_id[0])
                            update_document_in_container(transaction_executor,container_id,"LorryRecieptIds",lorry_reciept_id[0])
                            export_location_type = get_value_from_documentid(transaction_executor,Constants.SCENTITY_TABLE_NAME,export_location_id,"ScEntityTypeCode")##
                            if export_location_type == ['3']:
                                airway_bill_id = create_airway_bill(transaction_executor,manufacturer_id[0],actual_sc_entity_id, container_id, freight_carrier_id,export_location_id,import_location_id)
                                airway_bill_ids.append(airway_bill_id[0])
                                update_document_in_container(transaction_executor,container_id,"AirwayBillIds",airway_bill_id[0])
                            elif export_location_type == ['4']:
                                bill_of_lading_id = create_bill_of_lading(transaction_executor,manufacturer_id[0],actual_sc_entity_id, container_id,freight_carrier_id,export_location_id,import_location_id)
                                bill_of_lading_ids.append(bill_of_lading_id[0])
                                update_document_in_container(transaction_executor,container_id,"BillOfLadingIds",bill_of_lading_id[0])
                            
                            update_document(transaction_executor,Constants.CONTAINER_TABLE_NAME,"isPicked",container_id,True)
                            
                        else:
                            raise Exception("Order Already Picked!")

                    logger.info("=====================  O R D E R ====== P I C K E D ===================")
                    return lorry_reciept_ids, airway_bill_ids, bill_of_lading_ids
                    
                else:
                    raise Exception("Carrier Company is not approved.")
        else:
            raise Exception("Person not authorized for the pickup")
    else:
        raise Exception("Check Request Id")
Exemplo n.º 18
0
def approve_lading_bill(transaction_executor, bill_id, carrier_person_id):

    ## check if bill exist

    if document_exist(transaction_executor, Constants.AIRWAY_BILL_TABLE_NAME,
                      bill_id):
        ## authenticate air_person
        actual_sc_entity_id = get_scentityid_from_personid(
            transaction_executor, carrier_person_id)
        air_carrier_id = get_value_from_documentid(
            transaction_executor, Constants.AIRWAY_BILL_TABLE_NAME, bill_id,
            "CarrierId")
        print(actual_sc_entity_id)
        print(air_carrier_id)
        if actual_sc_entity_id == air_carrier_id[0]:
            # logger("Authorized!")
            container_id = get_value_from_documentid(
                transaction_executor, Constants.AIRWAY_BILL_TABLE_NAME,
                bill_id, "ContainerId")
            if lading_bill_already_approved(transaction_executor,
                                            "AirCarrierApproval", bill_id):
                raise Exception("Already Approved!")
            else:
                if isContainerSafe(transaction_executor, container_id[0]):
                    certificate_of_origin_id = get_value_from_documentid(
                        transaction_executor, Constants.CONTAINER_TABLE_NAME,
                        container_id[0], "CertificateOfOriginId")
                    packing_list_id = get_value_from_documentid(
                        transaction_executor, Constants.CONTAINER_TABLE_NAME,
                        container_id[0], "PackingListId")
                    custom_approved = (
                        document_already_approved_by_customs(
                            transaction_executor, "ExportApproval",
                            Constants.CERTIFICATE_OF_ORIGIN_TABLE_NAME,
                            certificate_of_origin_id[0])
                        and document_already_approved_by_customs(
                            transaction_executor, "ExportApproval",
                            Constants.PACKING_LIST_TABLE_NAME,
                            packing_list_id[0]))
                    if custom_approved:

                        update_document(transaction_executor,
                                        Constants.AIRWAY_BILL_TABLE_NAME,
                                        "AirCarrierApproval.isApproved",
                                        bill_id, True)
                        update_document(transaction_executor,
                                        Constants.AIRWAY_BILL_TABLE_NAME,
                                        "AirCarrierApproval.ApproverId",
                                        bill_id, carrier_person_id)
                    else:
                        raise Exception("Container not Approved By customs")
                else:
                    raise Exception(
                        "====A L A R M ==== CANNOT APPROVE=== CONTAINER DANGEROUS===="
                    )
        else:
            raise Exception("Not Authorized")

    elif document_exist(transaction_executor,
                        Constants.BILL_OF_LADING_TABLE_NAME, bill_id):
        ## authenticate Sea_person
        actual_sc_entity_id = get_scentityid_from_personid(
            transaction_executor, carrier_person_id)
        Sea_carrier_id = get_value_from_documentid(
            transaction_executor, Constants.BILL_OF_LADING_TABLE_NAME, bill_id,
            "SeaCarrierId")
        if actual_sc_entity_id == Sea_carrier_id[0]:
            # raise Exception("Authorized!")
            container_id = get_value_from_documentid(
                transaction_executor, Constants.BILL_OF_LADING_TABLE_NAME,
                bill_id, "ContainerId")
            if lading_bill_already_approved(transaction_executor,
                                            "SeaCarrierApproval", bill_id):
                raise Exception("Already Approved!")
            else:
                if isContainerSafe(transaction_executor, container_id):
                    certificate_of_origin_id = get_value_from_documentid(
                        transaction_executor, Constants.CONTAINER_TABLE_NAME,
                        container_id[0], "CertificateOfOrigin")
                    packing_list_id = get_value_from_documentid(
                        transaction_executor, Constants.CONTAINER_TABLE_NAME,
                        container_id[0], "PackingList")
                    already_approved = (
                        document_already_approved_by_customs(
                            transaction_executor, "ExportApproval",
                            Constants.CERTIFICATE_OF_ORIGIN_TABLE_NAME,
                            certificate_of_origin_id[0])
                        and document_already_approved_by_customs(
                            transaction_executor, "ExportApproval",
                            Constants.PACKING_LIST_TABLE_NAME,
                            packing_list_id[0]))

                    if already_approved:
                        update_document(transaction_executor,
                                        Constants.BILL_OF_LADING_TABLE_NAME,
                                        "SeaCarrierApproval.isApproved",
                                        bill_id, True)
                        update_document(transaction_executor,
                                        Constants.BILL_OF_LADING_TABLE_NAME,
                                        "SeaCarrierApproval.ApproverId",
                                        bill_id, carrier_person_id)
                    else:
                        raise Exception("Container not Approved By customs")
                else:
                    raise Exception(
                        "====A L A R M ==== CANNOT APPROVE=== CONTAINER DANGEROUS===="
                    )
        else:
            raise Exception("Not Authorized")
    else:
        raise Exception("Bill not found!")
Exemplo n.º 19
0
def initiate_distributor_shipment(transaction_executor, purchase_order_id, distributor_person_id,carrier_company_id,tranport_type):
    # check if po exist
    if document_exist(transaction_executor,Constants.PURCHASE_ORDER_TABLE_NAME,purchase_order_id):        
        # check if po is accepted
        if get_document_superadmin_approval_status(transaction_executor, Constants.SCENTITY_TABLE_NAME, carrier_company_id):
            if order_already_accepted(transaction_executor,purchase_order_id):
                
                #check for authorization
                required_scentity_id = get_sub_details(transaction_executor,Constants.PURCHASE_ORDER_TABLE_NAME,"Acceptor",purchase_order_id,"AcceptorScEntityId")
                actual_scentity_id = get_scentityid_from_personid(transaction_executor,distributor_person_id)
                if required_scentity_id[0] == actual_scentity_id:
                    # check if enough enventory for the order
                    inventory_table = inventory_table_already_exist(transaction_executor,actual_scentity_id)
                    product_id = get_value_from_documentid(transaction_executor,Constants.PURCHASE_ORDER_TABLE_NAME,purchase_order_id,"ProductId")
                    containers_ordered = get_value_from_documentid(transaction_executor,Constants.PURCHASE_ORDER_TABLE_NAME,purchase_order_id,"OrderQuantity")
                    containers_ordered = containers_ordered[0]
                    inventory_id =  next(get_document_ids(transaction_executor,inventory_table[0],"ProductId",product_id[0]))

                    available_unit_inventory = get_value_from_documentid(transaction_executor,inventory_table[0],inventory_id,"CurrentInventory")
                    available_unit_inventory = int(available_unit_inventory[0])
                    products_per_container = get_value_from_documentid(transaction_executor,Constants.PRODUCT_TABLE_NAME,product_id[0],"ProductsPerContainer")
                    product_units_ordered = int(containers_ordered) * int(products_per_container[0])
                    
                    if available_unit_inventory >= product_units_ordered:
                        print("=======================================")
                        containers_in_inventory = get_value_from_documentid(transaction_executor,inventory_table[0],inventory_id,"ContainerIds")
                        # containers_in_inventory = containers_in_inventory[0]
                        # lis = [containers_in_inventory,[1,2]]
                        containers_in_inventory = oneDArray(containers_in_inventory)
                        total_containers = len(containers_in_inventory)

                        print(containers_in_inventory)
                        
                        available_containers = int(available_unit_inventory/products_per_container[0])
                        starting_container = total_containers - (available_containers)
                        ending_container = starting_container + int(containers_ordered)
                        # for containers in range((1,containers_ordered+1)):
                        # assign the first containers to the new purchase order
                        assigned_container_ids = containers_in_inventory[starting_container:ending_container]

                        logger.info("Assigned ids are :{}".format(assigned_container_ids))
                        # add purchase order to the new container
                        for container_id in assigned_container_ids:
                            update_document(transaction_executor,Constants.CONTAINER_TABLE_NAME,"PurchaseOrderId",container_id, purchase_order_id)
                            update_document(transaction_executor,Constants.CONTAINER_TABLE_NAME,"CarrierId",container_id, carrier_company_id)
                            update_document(transaction_executor,Constants.CONTAINER_TABLE_NAME,"isDelivered",container_id, False)
                            update_document(transaction_executor,Constants.CONTAINER_TABLE_NAME,"TransportType",container_id, tranport_type)
                            update_document(transaction_executor,Constants.CONTAINER_TABLE_NAME,"isPicked",container_id,False)
                        
                        update_document(transaction_executor,Constants.PURCHASE_ORDER_TABLE_NAME,"HighestPackagingLevelIds",purchase_order_id,assigned_container_ids)
                        available_unit_inventory = available_unit_inventory - product_units_ordered
                        update_document(transaction_executor,inventory_table[0],"CurrentInventory",inventory_id,available_unit_inventory)

                        pick_up_request_id = create_pick_up_request(transaction_executor,actual_scentity_id,carrier_company_id, purchase_order_id, tranport_type)
                        logger.info("===================== S H I P M E N T ======= I N I T I A T E D =======================")
                        return pick_up_request_id[0]
                    
                    else:
                        raise Exception("Not enough dosage in inventory to initiate shipment.")
                else:
                    raise Exception("Person not Authorized!")
            else:
                raise Exception("Accept the Order First!")
        else:
            raise Exception(" Carrier Company is not Approved")
    else:
        raise Exception("Cannot Locate Purchase Order.")
Exemplo n.º 20
0
def custom_approval(transaction_executor, container_id, approval_type,
                    customs_person_id):
    if document_exist(transaction_executor, Constants.CONTAINER_TABLE_NAME,
                      container_id):
        scentity_id = get_scentityid_from_personid(transaction_executor,
                                                   customs_person_id)
        ## we will just check if person is a custom agent. and then airway bill/bill of lading will be made from the point where custom agen works
        print(scentity_id)
        scentity_type_code = get_value_from_documentid(
            transaction_executor, Constants.SCENTITY_TABLE_NAME, scentity_id,
            "ScEntityTypeCode")
        if scentity_type_code[0] == '3':
            # logger.info("Customs Agent confirmed")
            airway_bills = get_value_from_documentid(
                transaction_executor, Constants.CONTAINER_TABLE_NAME,
                container_id, "AirwayBillIds")
            destination_id = get_value_from_documentid(
                transaction_executor, Constants.AIRWAY_BILL_TABLE_NAME,
                airway_bills[0][-1],
                "{}".format(approval_type[:6]) + "AirportId")

            if scentity_id == destination_id[0]:
                # logger.info("Custom Agent belongs to {} airport.".format(approval_type[:6]))

                if get_document_superadmin_approval_status(
                        transaction_executor, Constants.SCENTITY_TABLE_NAME,
                        scentity_id):
                    if isContainerSafe(transaction_executor, container_id):
                        ##check if container is safe:
                        certificateofOrigin = get_value_from_documentid(
                            transaction_executor,
                            Constants.CONTAINER_TABLE_NAME, container_id,
                            "CertificateOfOriginId")
                        packinglist = get_value_from_documentid(
                            transaction_executor,
                            Constants.CONTAINER_TABLE_NAME, container_id,
                            "PackingListId")
                        already_approved = (
                            document_already_approved_by_customs(
                                transaction_executor, approval_type,
                                Constants.CERTIFICATE_OF_ORIGIN_TABLE_NAME,
                                certificateofOrigin[0])
                            and document_already_approved_by_customs(
                                transaction_executor, approval_type,
                                Constants.PACKING_LIST_TABLE_NAME,
                                packinglist[0]))

                        if already_approved:
                            raise Exception("Documents were already approved!")
                        else:
                            if approval_type == "ExportApproval":
                                lorry_reciepts = get_value_from_documentid(
                                    transaction_executor,
                                    Constants.CONTAINER_TABLE_NAME,
                                    container_id, "LorryRecieptIds")
                                update_document(
                                    transaction_executor,
                                    Constants.LORRY_RECEIPT_TABLE_NAME,
                                    "isDeliveryDone", lorry_reciepts[0][-1],
                                    True)
                                update_document(
                                    transaction_executor,
                                    Constants.LORRY_RECEIPT_TABLE_NAME,
                                    "DeliveryTime", lorry_reciepts[0][-1],
                                    datetime.datetime.now().timestamp())

                            update_document(
                                transaction_executor,
                                Constants.CERTIFICATE_OF_ORIGIN_TABLE_NAME,
                                "{}.isApprovedByCustoms".format(approval_type),
                                certificateofOrigin[0], True)
                            update_document(
                                transaction_executor,
                                Constants.CERTIFICATE_OF_ORIGIN_TABLE_NAME,
                                "{}.ApproverId".format(approval_type),
                                certificateofOrigin[0], customs_person_id)
                            update_document(
                                transaction_executor,
                                Constants.PACKING_LIST_TABLE_NAME,
                                "{}.isApprovedByCustoms".format(approval_type),
                                packinglist[0], True)
                            update_document(
                                transaction_executor,
                                Constants.PACKING_LIST_TABLE_NAME,
                                "{}.ApproverId".format(approval_type),
                                packinglist[0], customs_person_id)
                            logger.info(
                                "===================== C O N T A I N E R =========== C U S T O M ===========A P P R O V E D ==========="
                            )
                    else:
                        raise Exception(
                            "====A L A R M ==== CANNOT APPROVE=== CONTAINER DANGEROUS===="
                        )
                else:
                    raise Exception("Airport not confirmed yet.")
            else:
                raise Exception("Custom Agent doesn't belong to this airport")

        elif scentity_type_code[0] == '4':
            logger.info("Customs Agent confirmed")
            bill_of_ladings = get_value_from_documentid(
                transaction_executor, Constants.CONTAINER_TABLE_NAME,
                container_id, "BillOfLadingIds")
            destination_id = get_value_from_documentid(
                transaction_executor, Constants.BILL_OF_LADING_TABLE_NAME,
                bill_of_ladings[0][-1],
                "{}".format(approval_type[:6]) + "portId")

            if scentity_id == destination_id[0]:
                logger.info("Custom Agent belongs to {} airport.".format(
                    approval_type[:6]))

                if get_document_superadmin_approval_status(
                        transaction_executor, Constants.SCENTITY_TABLE_NAME,
                        scentity_id):
                    if isContainerSafe(transaction_executor, container_id):
                        ##check if container is safe:

                        certificateofOrigin = get_value_from_documentid(
                            transaction_executor,
                            Constants.CONTAINER_TABLE_NAME, container_id,
                            "CertificateOfOriginId")
                        packinglist = get_value_from_documentid(
                            transaction_executor,
                            Constants.CONTAINER_TABLE_NAME, container_id,
                            "PackingListId")
                        already_approved = (
                            document_already_approved_by_customs(
                                transaction_executor, approval_type,
                                Constants.CERTIFICATE_OF_ORIGIN_TABLE_NAME,
                                certificateofOrigin[0])
                            and document_already_approved_by_customs(
                                transaction_executor, approval_type,
                                Constants.PACKING_LIST_TABLE_NAME,
                                packinglist[0]))

                        if already_approved:
                            logger.info("Documents were already approved!")
                        else:
                            logger.info("approving CoO and PL")
                            lorry_reciepts = get_value_from_documentid(
                                transaction_executor,
                                Constants.CONTAINER_TABLE_NAME, container_id,
                                "LorryRecieptIds")
                            update_document(transaction_executor,
                                            Constants.LORRY_RECEIPT_TABLE_NAME,
                                            "isDeliveryDone",
                                            lorry_reciepts[0][-1], True)
                            update_document(
                                transaction_executor,
                                Constants.CERTIFICATE_OF_ORIGIN_TABLE_NAME,
                                "{}.isApprovedByCustoms".format(approval_type),
                                certificateofOrigin[0], True)
                            update_document(
                                transaction_executor,
                                Constants.CERTIFICATE_OF_ORIGIN_TABLE_NAME,
                                "{}.ApproverId".format(approval_type),
                                certificateofOrigin[0], customs_person_id)

                            update_document(
                                transaction_executor,
                                Constants.PACKING_LIST_TABLE_NAME,
                                "{}.isApprovedByCustoms".format(approval_type),
                                packinglist[0], True)
                            update_document(
                                transaction_executor,
                                Constants.PACKING_LIST_TABLE_NAME,
                                "{}.ApproverId".format(approval_type),
                                packinglist[0], customs_person_id)
                            logger.info(
                                "===================== C O N T A I N E R =========== C U S T O M ===========A P P R O V E D ==========="
                            )
                    else:
                        raise Exception(
                            "====A L A R M ==== CANNOT APPROVE=== CONTAINER DANGEROUS===="
                        )
                else:
                    raise Exception("Airport not confirmed yet.")
            else:
                raise Exception("Agent not Authorized.")
        else:
            raise Exception("Person not Custom Agent")
    else:
        raise Exception("Container not found!")
Exemplo n.º 21
0
def deliver_product_to_distributor(transaction_executor,pick_up_request_id,pick_up_person_id):
    if document_exist(transaction_executor,Constants.PICK_UP_REQUESTS_TABLE,pick_up_request_id):
        update_document(transaction_executor,Constants.PICK_UP_REQUESTS_TABLE,"isAccepted",pick_up_request_id,True)
        purchase_order_id = get_value_from_documentid(transaction_executor,Constants.PICK_UP_REQUESTS_TABLE, pick_up_request_id, "PurchaseOrderId")
        purchase_order_id = purchase_order_id[0]
        container_ids = get_value_from_documentid(transaction_executor,Constants.PURCHASE_ORDER_TABLE_NAME,purchase_order_id,"HighestPackagingLevelIds")
        for container_id in container_ids[0]:   
            total_containers_ordered = len(container_ids[0]) 
            if document_exist(transaction_executor,Constants.CONTAINER_TABLE_NAME,container_id):
            #check if container_exist
                certificate_of_origin_id = get_value_from_documentid(transaction_executor,Constants.CONTAINER_TABLE_NAME,container_id,"CertificateOfOriginId")
                packing_list_id = get_value_from_documentid(transaction_executor, Constants.CONTAINER_TABLE_NAME,container_id,"PackingListId")
                import_custom_approved = (document_already_approved_by_customs(transaction_executor,"ImportApproval",Constants.CERTIFICATE_OF_ORIGIN_TABLE_NAME,certificate_of_origin_id[0]) and
                document_already_approved_by_customs(transaction_executor,"ImportApproval", Constants.PACKING_LIST_TABLE_NAME,packing_list_id[0]))

                if import_custom_approved:
                    # logger.info("Approved by Import!")
                    total_safe_containers = copy.copy(total_containers_ordered)
                    if isContainerSafe(transaction_executor,container_id):
                        actual_sc_entity_id = get_scentityid_from_personid(transaction_executor,pick_up_person_id)
                        transport_type = get_value_from_documentid(transaction_executor,Constants.CONTAINER_TABLE_NAME,container_id,"TransportType")
                        
                        #check if container is safe
                        if transport_type[0] == 1:
                            table = Constants.AIRWAY_BILL_TABLE_NAME
                            airway_bills = get_value_from_documentid(transaction_executor,Constants.CONTAINER_TABLE_NAME,container_id,"AirwayBillIds")
                            
                        elif transport_type[0] == 2:
                            table = Constants.BILL_OF_LADING_TABLE_NAME
                            bill_of_lading = get_value_from_documentid(transaction_executor,Constants.CONTAINER_TABLE_NAME,container_id,"BillOfLadingIds")


                        pick_up_scentity_id = get_value_from_documentid(transaction_executor,Constants.PICK_UP_REQUESTS_TABLE,pick_up_request_id, "CarrierCompanyId")
                        if actual_sc_entity_id == pick_up_scentity_id[0]:
                            # logger.info("Authorized!")

                            
                            if transport_type[0] == 1:
                                is_picked_up = get_sub_details(transaction_executor,table,"RecieverApproval",airway_bills[0][-1],"isApproved")
                                if is_picked_up[0] == 0:
                                    update_document(transaction_executor,Constants.AIRWAY_BILL_TABLE_NAME,"RecieverApproval.isApproved",airway_bills[0][-1],True)
                                    update_document(transaction_executor,Constants.AIRWAY_BILL_TABLE_NAME,"RecieverApproval.ApproverId",airway_bills[0][-1], pick_up_person_id)
                                    pick_up_location = get_value_from_documentid(transaction_executor,Constants.AIRWAY_BILL_TABLE_NAME,airway_bills[0][-1],"ImportAirportName")
                                    consignee_id = get_value_from_documentid(transaction_executor,Constants.AIRWAY_BILL_TABLE_NAME,airway_bills[0][-1],"SenderScEntityId")
                                else:
                                    raise Exception("container already picked up")

                            elif transport_type[0] == 2:
                                is_picked_up = get_sub_details(transaction_executor,table,"RecieverApproval",bill_of_lading[0][-1],"isApproved")
                                if is_picked_up[0] == 0:
                                    update_document(transaction_executor,Constants.BILL_OF_LADING_TABLE_NAME,"RecieverApproval.isApproved",bill_of_lading[0][-1],True)
                                    update_document(transaction_executor,Constants.BILL_OF_LADING_TABLE_NAME,"RecieverApproval.ApproverId",bill_of_lading[0][-1], pick_up_person_id)
                                    pick_up_location = get_value_from_documentid(transaction_executor,Constants.BILL_OF_LADING_TABLE_NAME,bill_of_lading[0][-1],"ImportPortName")
                                    consignee_id = get_value_from_documentid(transaction_executor,Constants.BILL_OF_LADING_TABLE_NAME,bill_of_lading[0][-1],"SenderScEntityId")
                                else:
                                    raise Exception("Container Already picked up")

                            consignee_name = get_value_from_documentid(transaction_executor,Constants.SCENTITY_TABLE_NAME,consignee_id[0],"ScEntityName")
                            delivery_location = get_scentity_contact(transaction_executor,actual_sc_entity_id[0],"Address")
                            lorry_reciepts = get_value_from_documentid(transaction_executor,Constants.CONTAINER_TABLE_NAME,container_id,"LorryRecieptIds")
                            carrier_id = get_value_from_documentid(transaction_executor,Constants.LORRY_RECEIPT_TABLE_NAME,lorry_reciepts[0][-1],"CarrierId")
                            if carrier_id[0] == pick_up_scentity_id[0]:
                                # logger.info("No request was made by buyer to pickup. Creating a new L/R to initiate import delivery.")
                                lorry_reciept_id = create_lorry_reciept(transaction_executor,actual_sc_entity_id,pick_up_person_id,pick_up_location[0],delivery_location,consignee_id,consignee_name,True)
                                update_document_in_container(transaction_executor,container_id,"LorryRecieptIds",lorry_reciept_id[0])
                            else:
                                # logger.info("Pick up request was made by new carrier assigned by buyer.")
                                update_document(transaction_executor,Constants.LORRY_RECEIPT_TABLE_NAME,"isPickedUp",lorry_reciepts[0][-1],True)
                            
                            logger.info(" ============ I M P O R T ========== P I C K U P ========S U C C E S S F U L =============")

                        else:
                            raise Exception("Not Authorized!")
                    else:
                        # raise Exception("Container Not Safe!")
                        total_safe_containers = total_safe_containers - 1
                        if total_safe_containers > 0:
                            continue
                        else:
                            raise Exception("Not Container was safe. Pick up can't be made for any container")
                         
                else:
                    raise Exception("Not approved by Customs.")
            else:
                raise Exception("Check Container Id")
             #check if pick up person is authorized
    else:
        raise Exception(" Check Request Id")
def create_purchase_order_to_manufacturer(transaction_executor, person_id,
                                          purchase_order_details):

    product_id = purchase_order_details["ProductId"]
    #check if the product exist and approved
    if product_exists(transaction_executor, product_id):
        # logger.info("Product Found!")
        order_quantity = purchase_order_details["OrderQuantity"]
        ##check if the product is approved
        if get_document_superadmin_approval_status(
                transaction_executor, Constants.PRODUCT_TABLE_NAME,
                product_id):
            #check if the orderQuantity is less than greater than
            if (isinstance(order_quantity, int)
                ):  #<<--------------- have to convery orderquantity to float
                min_selling_amount_containers = get_value_from_documentid(
                    transaction_executor, Constants.PRODUCT_TABLE_NAME,
                    product_id, "MinimumSellingAmount")
                if order_quantity >= min_selling_amount_containers[0]:
                    scentity_id = get_scentityid_from_personid(
                        transaction_executor, person_id)
                    if scentity_id:
                        #check if the orderer company is approved
                        if get_document_superadmin_approval_status(
                                transaction_executor,
                                Constants.SCENTITY_TABLE_NAME, scentity_id):
                            purchase_order_number = get_index_number(
                                transaction_executor,
                                Constants.PURCHASE_ORDER_TABLE_NAME,
                                "PurchaseOrderNumber")
                            purchase_order_details.update(
                                {"PurchaseOrderNumber": purchase_order_number})
                            purchase_order_details.update(
                                {"OrderType": "1"}
                            )  ## order type 1 is by distributor to manufacturer
                            ## order type 2 is to distributor by downstream entities
                            purchase_order_details['Orderer'].update(
                                {'OrdererScEntityId': scentity_id})
                            purchase_order_details['Orderer'].update(
                                {'OrdererPersonId': person_id})
                            sc_entity_type_code = get_value_from_documentid(
                                transaction_executor,
                                Constants.SCENTITY_TABLE_NAME, scentity_id,
                                "ScEntityTypeCode")
                            if sc_entity_type_code[
                                    0] == "2":  ## normal company
                                highest_packaging_level = "Container"
                            # logger.info(purchase_order_details)

                            product_id = purchase_order_details["ProductId"]
                            manufacturer_id = get_value_from_documentid(
                                transaction_executor,
                                Constants.PRODUCT_TABLE_NAME, product_id,
                                "ManufacturerId")

                            ## highest packagin level Id in this case is container since that is the minimum amount that distributor has to order

                            purchase_order = {
                                **purchase_order_details, "Acceptor": {
                                    "isOrderAccepted": False,
                                    "AcceptorScEntityId": manufacturer_id[0],
                                    "ApprovingPersonId": ""
                                },
                                "InvoiceId":
                                "",
                                "HighestPackagingLevelIds": [],
                                "HighestPackagingLevelType":
                                highest_packaging_level
                            }
                            purchase_order_id = insert_documents(
                                transaction_executor,
                                Constants.PURCHASE_ORDER_TABLE_NAME,
                                convert_object_to_ion(purchase_order))

                            # logger.info("Order was placed sucessfully with id: {}".format(purchase_order_id))
                            logger.info(
                                " ================================== O R D E R =========== P L A C E D ==============================="
                            )
                            return purchase_order_id[0]
                        else:
                            raise Exception(
                                "OrdererComany is not approved by the Admin.")
                    else:
                        raise Exception(
                            "check if person id is associated with an entity.")
                else:
                    raise Exception(
                        "Order quantity cannot be less than minimum quantity.")
            else:
                raise Exception(
                    "Order Quantity can only be in the form of integers.")
        else:
            raise Exception(
                "Product is not approved yet. Wait for the product to get approved first."
            )
    else:
        raise Exception(" Product Id is wrong!")
Exemplo n.º 23
0
def initiate_shipment(transaction_executor, carrier_company_id, transport_type,
                      purchase_order_id, person_id):
    if document_exist(transaction_executor,
                      Constants.PURCHASE_ORDER_TABLE_NAME, purchase_order_id):
        # logger.info("Purchase Order Found!")
        if get_document_superadmin_approval_status(
                transaction_executor, Constants.SCENTITY_TABLE_NAME,
                carrier_company_id):
            product_id = get_value_from_documentid(
                transaction_executor, Constants.PURCHASE_ORDER_TABLE_NAME,
                purchase_order_id, "ProductId")
            product_id = product_id[0]
            required_scentity_id = get_sub_details(
                transaction_executor, Constants.PURCHASE_ORDER_TABLE_NAME,
                "Acceptor", purchase_order_id, "AcceptorScEntityId")
            actual_scentity_id = get_scentityid_from_personid(
                transaction_executor, person_id)
            if required_scentity_id[0] == actual_scentity_id:
                # logger.info("Authorized!")
                batch_table_id = batch_table_exist(transaction_executor,
                                                   product_id)
                if order_already_accepted(transaction_executor,
                                          purchase_order_id):
                    if shipment_already_started(transaction_executor,
                                                purchase_order_id):
                        raise Exception('Shipment already started.')
                    else:
                        if batch_table_id:
                            batch_table_name = get_tableName_from_tableId(
                                transaction_executor, batch_table_id)

                            products_per_container = get_value_from_documentid(
                                transaction_executor,
                                Constants.PRODUCT_TABLE_NAME, product_id,
                                "ProductsPerContainer")
                            # min_selling_amount = int(min_selling_amount_containers[0])*int(products_per_container[0])
                            products_per_case = round(
                                (products_per_container[0] /
                                 (Constants.CASES_PER_PALLETE *
                                  Constants.PALLETS_PER_CONTAINER)))
                            # logger.info("products_per_case is : {}".format(products_per_case))
                            product_units_ordered = enough_inventory_registered_for_order(
                                transaction_executor, products_per_case,
                                purchase_order_id, batch_table_name)
                            if product_units_ordered:
                                # logger.info("Units Ordered are: {}".format(product_units_ordered))
                                update_document(
                                    transaction_executor,
                                    Constants.PURCHASE_ORDER_TABLE_NAME,
                                    "isOrderShipped", purchase_order_id, True)
                                product_code = get_value_from_documentid(
                                    transaction_executor,
                                    Constants.PRODUCT_TABLE_NAME, product_id,
                                    "ProductCode")
                                case_ids = assign_products_into_case(
                                    transaction_executor, product_id,
                                    batch_table_name, product_units_ordered,
                                    products_per_case, purchase_order_id,
                                    product_code)
                                pallete_ids = assign_cases_into_pallete(
                                    transaction_executor, case_ids,
                                    product_code)
                                certificate_of_origin_id = create_certificate_of_origin(
                                    transaction_executor, product_id)
                                # product_quantity = get_value_from_documentid(transaction_executor,Constants.PRODUCT_TABLE_NAME,product_id,"MinimumSellingAmount")
                                container_ids = assign_palletes_into_container(
                                    transaction_executor, pallete_ids,
                                    product_code, purchase_order_id,
                                    carrier_company_id,
                                    certificate_of_origin_id[0],
                                    products_per_container, transport_type)
                                update_container_ids_in_purchase_order(
                                    transaction_executor, container_ids,
                                    purchase_order_id)

                                pick_up_request_id = create_pick_up_request(
                                    transaction_executor, actual_scentity_id,
                                    carrier_company_id, purchase_order_id,
                                    transport_type)

                                logger.info(
                                    "===================== S H I P M E N T ======= I N I T I A T E D ======================="
                                )
                                return pick_up_request_id[0], container_ids
                            else:
                                raise Exception(
                                    " First produce and register the vaccines into the sytem before shipping them"
                                )
                        else:
                            raise Exception(
                                'Register the Batch table first by inputting inventory!'
                            )
                else:
                    raise Exception("Accept the order first!")
            else:
                raise Exception("Not authorized!")
        else:
            raise Exception("Carrier company is not approved by MCG.")
    else:
        raise Exception("order doesn't exist")
Exemplo n.º 24
0
def deliver_product_to_final_entity(transaction_executor, pick_up_request_id,
                                    truck_carrier_person_id):
    if document_exist(transaction_executor, Constants.PICK_UP_REQUESTS_TABLE,
                      pick_up_request_id):
        update_document(transaction_executor, Constants.PICK_UP_REQUESTS_TABLE,
                        "isAccepted", pick_up_request_id, True)
        purchase_order_id = get_value_from_documentid(
            transaction_executor, Constants.PICK_UP_REQUESTS_TABLE,
            pick_up_request_id, "PurchaseOrderId")
        purchase_order_id = purchase_order_id[0]

        if document_exist(transaction_executor,
                          Constants.PURCHASE_ORDER_TABLE_NAME,
                          purchase_order_id):
            container_ids = get_value_from_documentid(
                transaction_executor, Constants.PURCHASE_ORDER_TABLE_NAME,
                purchase_order_id, "HighestPackagingLevelIds")

            carrier_company_id = get_value_from_documentid(
                transaction_executor, Constants.CONTAINER_TABLE_NAME,
                container_ids[0][0], "CarrierCompanyId")

            actual_sc_entity_id = get_scentityid_from_personid(
                transaction_executor, truck_carrier_person_id)

            if carrier_company_id[0] == actual_sc_entity_id:
                lorry_reciept_ids = []
                for container_id in container_ids[0]:
                    if isContainerSafe(transaction_executor, container_id):
                        isPicked = get_value_from_documentid(
                            transaction_executor,
                            Constants.CONTAINER_TABLE_NAME, container_id,
                            "isPicked")

                        if isPicked[0] == 0:
                            update_document(
                                transaction_executor,
                                Constants.PURCHASE_ORDER_TABLE_NAME,
                                "isOrderShipped", purchase_order_id, True)
                            update_document(transaction_executor,
                                            Constants.CONTAINER_TABLE_NAME,
                                            "isPicked", container_id, True)

                            consignee_id = get_sub_details(
                                transaction_executor,
                                Constants.PURCHASE_ORDER_TABLE_NAME, "Orderer",
                                purchase_order_id, "OrdererScEntityId")
                            pick_up_location = get_scentity_contact(
                                transaction_executor, consignee_id[0],
                                "Address")
                            consignee_name = get_value_from_documentid(
                                transaction_executor,
                                Constants.SCENTITY_TABLE_NAME, consignee_id[0],
                                "ScEntityName")
                            acceptor_id = get_sub_details(
                                transaction_executor,
                                Constants.PURCHASE_ORDER_TABLE_NAME,
                                "Acceptor", purchase_order_id,
                                "AcceptorScEntityId")
                            delivery_location = get_scentity_contact(
                                transaction_executor, acceptor_id[0],
                                "Address")

                            #change consignee id to person who made pick-up request
                            lorry_reciept_id = create_lorry_reciept(
                                transaction_executor, actual_sc_entity_id,
                                truck_carrier_person_id, pick_up_location[0],
                                delivery_location[0], consignee_id[0],
                                consignee_name[0], True)
                            lorry_reciept_ids.append(lorry_reciept_id[0])

                        else:
                            raise Exception("Order Already Picked")
                    else:
                        raise Exception(" Container is not Safe for Delivery!")

                logger.info(
                    " =========== L O C A L ====== T R A N S P O R T ======== I N I T I A T E D ============= "
                )
                return lorry_reciept_ids
            else:
                raise Exception(" Not Authorized! ")
        else:
            raise Exception(" Check Purchase Order Id.")
    else:
        raise Exception("Check Request Id")
Exemplo n.º 25
0
def person_is_superadmin(transaction_executor,person_id):
    is_superadmin = get_value_from_documentid(transaction_executor,Constants.PERSON_TABLE_NAME,person_id,"isSuperAdmin")
    if is_superadmin == [1]:
        return True
    else:
        return False
Exemplo n.º 26
0
def create_purchase_order_to_distributor(transaction_executor,
                                         purchase_order_details,
                                         distributor_id, hospital_person_id):

    product_id = purchase_order_details["ProductId"]
    number_of_containers_ordered = purchase_order_details["OrderQuantity"]

    if document_exist(transaction_executor, Constants.SCENTITY_TABLE_NAME,
                      distributor_id):
        # check person belong to ScEntity
        actual_sc_entity_id = get_scentityid_from_personid(
            transaction_executor, hospital_person_id)
        if actual_sc_entity_id:
            manufacturer_id = get_value_from_documentid(
                transaction_executor, Constants.PRODUCT_TABLE_NAME, product_id,
                "ManufacturerId")
            # print(manufacturer_id)
            if manufacturer_id[0] != distributor_id:
                # scentity_type_code = get_value_from_documentid(transaction_executor,Constants.SCENTITY_TABLE_NAME,distributor_id,"ScEntityTypeCode")
                # logger.info("Distributor confirmed")
                inventory_table = inventory_table_already_exist(
                    transaction_executor, distributor_id)
                if inventory_table:
                    #check product exist with distributor
                    if product_exist_in_inventory(transaction_executor,
                                                  inventory_table[0],
                                                  product_id):
                        # check number of dosage are in muliple of cases and more than minumum amount
                        inventory_id = next(
                            get_document_ids(transaction_executor,
                                             inventory_table[0], "ProductId",
                                             product_id))
                        minimum_containers_order = get_value_from_documentid(
                            transaction_executor, inventory_table[0],
                            inventory_id, "MinimumSellingAmount")

                        if number_of_containers_ordered >= minimum_containers_order[
                                0] and isinstance(number_of_containers_ordered,
                                                  int):

                            purchase_order_number = get_index_number(
                                transaction_executor,
                                Constants.PURCHASE_ORDER_TABLE_NAME,
                                "PurchaseOrderNumber")
                            purchase_order_details.update({"OrderType": "2"})
                            purchase_order_details.update(
                                {"PurchaseOrderNumber": purchase_order_number})
                            purchase_order_details['Orderer'].update(
                                {'OrdererScEntityId': actual_sc_entity_id})
                            purchase_order_details['Orderer'].update(
                                {'OrdererPersonId': hospital_person_id})
                            purchase_order = {
                                **purchase_order_details, "Acceptor": {
                                    "isOrderAccepted": False,
                                    "AcceptorScEntityId": distributor_id,
                                    "ApprovingPersonId": ""
                                },
                                "InvoiceId": "",
                                "HighestPackagingLevelIds": [],
                                "HighestPackagingLevelType": "Containers"
                            }
                            purchase_order_id = insert_documents(
                                transaction_executor,
                                Constants.PURCHASE_ORDER_TABLE_NAME,
                                convert_object_to_ion(purchase_order))
                            # logger.info("Order was placed sucessfully with id: {}".format(purchase_order_id))
                            logger.info(
                                " ================================== O R D E R =========== P L A C E D ==============================="
                            )
                            return purchase_order_id[0]

                        else:
                            raise Exception(
                                "Number of dosage must be an integer and greater than {} "
                                .format(minimum_containers_order))
                    else:
                        raise Exception(
                            "Distributor doesn't have this product.")
                else:
                    raise Exception("Distributor does not have any inventory")
            else:
                raise Exception(
                    "Order is being placed to wrong entity. Check Distributor_id"
                )
        else:
            raise Exception("Check the person id!")
    else:
        raise Exception(" Check Distributor id!")
Exemplo n.º 27
0
def approve_order_delivery(transaction_executor, purchase_order_id, person_id):
    if document_exist(transaction_executor,
                      Constants.PURCHASE_ORDER_TABLE_NAME, purchase_order_id):
        orderer_id = get_orderer_id(transaction_executor, purchase_order_id)
        actual_sc_entity_id = get_scentityid_from_personid(
            transaction_executor, person_id)
        order_quantity = get_value_from_documentid(
            transaction_executor, Constants.PURCHASE_ORDER_TABLE_NAME,
            purchase_order_id, "OrderQuantity")
        product_id = get_value_from_documentid(
            transaction_executor, Constants.PURCHASE_ORDER_TABLE_NAME,
            purchase_order_id, "ProductId")
        if actual_sc_entity_id == orderer_id:
            delivered_container_ids = []
            delivered_pallete_ids = []
            delivered_cases_ids = []
            delivered_product_instances = []
            delivered_product_quantity = 0
            container_ids = get_value_from_documentid(
                transaction_executor, Constants.PURCHASE_ORDER_TABLE_NAME,
                purchase_order_id, "HighestPackagingLevelIds")
            invoice_id = get_value_from_documentid(
                transaction_executor, Constants.PURCHASE_ORDER_TABLE_NAME,
                purchase_order_id, "InvoiceId")
            update_document(transaction_executor, Constants.INVOICE_TABLE_NAME,
                            "Approval.isInvoiceApprovedForPayment",
                            invoice_id[0], True)
            update_document(transaction_executor, Constants.INVOICE_TABLE_NAME,
                            "Approval.ApproverId", invoice_id[0], True)

            for container_id in container_ids[0]:

                certificate_of_origin_id = get_value_from_documentid(
                    transaction_executor, Constants.CONTAINER_TABLE_NAME,
                    container_id, "CertificateOfOriginId")
                packing_list_id = get_value_from_documentid(
                    transaction_executor, Constants.CONTAINER_TABLE_NAME,
                    container_id, "PackingListId")
                if isContainerSafe:

                    is_container_delivered = get_value_from_documentid(
                        transaction_executor, Constants.CONTAINER_TABLE_NAME,
                        container_id, "isDelivered")
                    if is_container_delivered == [0]:

                        import_custom_approved = (
                            document_already_approved_by_customs(
                                transaction_executor, "ImportApproval",
                                Constants.CERTIFICATE_OF_ORIGIN_TABLE_NAME,
                                certificate_of_origin_id[0])
                            and document_already_approved_by_customs(
                                transaction_executor, "ImportApproval",
                                Constants.PACKING_LIST_TABLE_NAME,
                                packing_list_id[0]))

                        if import_custom_approved:
                            update_document(transaction_executor,
                                            Constants.CONTAINER_TABLE_NAME,
                                            "isDelivered", container_id, True)
                            lorry_reciepts = get_value_from_documentid(
                                transaction_executor,
                                Constants.CONTAINER_TABLE_NAME, container_id,
                                "LorryRecieptIds")
                            update_document(transaction_executor,
                                            Constants.LORRY_RECEIPT_TABLE_NAME,
                                            "isDeliveryDone",
                                            lorry_reciepts[0][-1], True)
                            update_document(
                                transaction_executor,
                                Constants.LORRY_RECEIPT_TABLE_NAME,
                                "DeliveryTime", lorry_reciepts[0][-1],
                                datetime.datetime.now().timestamp())
                            delivered_container_ids.append(container_id)

                            packing_list_id = get_value_from_documentid(
                                transaction_executor,
                                Constants.CONTAINER_TABLE_NAME, container_id,
                                "PackingListId")
                            pallete_ids = get_value_from_documentid(
                                transaction_executor,
                                Constants.PACKING_LIST_TABLE_NAME,
                                packing_list_id[0], "PalleteIds")
                            # pallete_ids = oneDArray(pallete_ids)
                            delivered_pallete_ids.append(pallete_ids[0])
                            case_ids = get_value_from_documentid(
                                transaction_executor,
                                Constants.PACKING_LIST_TABLE_NAME,
                                packing_list_id[0], "CasesIds")
                            case_ids = oneDArray(case_ids[0])

                            delivered_cases_ids.append(case_ids)
                            product_quantity = get_value_from_documentid(
                                transaction_executor,
                                Constants.PACKING_LIST_TABLE_NAME,
                                packing_list_id[0], "ProductQuantity")
                            # print(product_quantity[0])
                            delivered_product_quantity = delivered_product_quantity + int(
                                product_quantity[0][0])

                            for case_id in case_ids:

                                product_instances = get_value_from_documentid(
                                    transaction_executor,
                                    Constants.CASES_TABLE_NAME, case_id,
                                    "ProductInstances")
                                delivered_product_instances.append(
                                    product_instances[0])
                        else:
                            raise Exception(
                                "Container Not Approved by Import Customs")
                    else:
                        raise Exception("Container Already Delivered")
                else:
                    raise Exception(
                        "A L A R M================C O N T A I N E R=======N O T=======S A F E =========="
                    )
            delivered_pallete_ids = reduce(lambda x, y: x + y,
                                           delivered_pallete_ids)
            delivered_cases_ids = reduce(lambda x, y: x + y,
                                         delivered_cases_ids)
            delivered_product_instances = oneDArray(
                delivered_product_instances)
            containers_delivered = len(delivered_container_ids)

            invoice_id = get_value_from_documentid(
                transaction_executor, Constants.PURCHASE_ORDER_TABLE_NAME,
                purchase_order_id, "InvoiceId")
            if order_quantity[0] == containers_delivered:

                update_document(transaction_executor,
                                Constants.INVOICE_TABLE_NAME, "OrderQuantity",
                                invoice_id[0], containers_delivered)
                # logger.info("all containers delivered without damage ")
            elif order_quantity[0] > containers_delivered:
                # logger.info("{} containers were damaged in the tranport. Updating new order quantity and order value.".format(order_quantity[0]-containers_delivered))
                update_document(transaction_executor,
                                Constants.INVOICE_TABLE_NAME, "OrderQuantity",
                                invoice_id[0], containers_delivered)
                product_id = get_value_from_documentid(
                    transaction_executor, Constants.PURCHASE_ORDER_TABLE_NAME,
                    purchase_order_id, "ProductId")
                product_price = get_value_from_documentid(
                    transaction_executor, Constants.PRODUCT_TABLE_NAME,
                    product_id[0], "ProductPrice")
                new_order_value = containers_delivered * product_price[0]
                update_document(transaction_executor,
                                Constants.INVOICE_TABLE_NAME, "OrderValue",
                                invoice_id[0], new_order_value)

            ###### update inventory #####################
            update_product_inventory(
                transaction_executor, actual_sc_entity_id, product_id[0],
                delivered_product_instances, delivered_cases_ids,
                delivered_pallete_ids, delivered_container_ids,
                delivered_product_quantity)

        else:
            raise Exception("Access Denied")
    else:
        raise Exception("Purchase Order does not exist.")
Exemplo n.º 28
0
def request_to_change_pickup(transaction_executor, purchase_order_id,
                             buyer_person_id, new_truck_carrier_id):
    if document_exist(transaction_executor,
                      Constants.PURCHASE_ORDER_TABLE_NAME, purchase_order_id):
        orderer_id = get_orderer_id(transaction_executor, purchase_order_id)
        actual_sc_entity_id = get_scentityid_from_personid(
            transaction_executor, buyer_person_id)

        if actual_sc_entity_id == orderer_id:
            container_ids = get_value_from_documentid(
                transaction_executor, Constants.PURCHASE_ORDER_TABLE_NAME,
                purchase_order_id, "HighestPackagingLevelIds")

            for container_id in container_ids[0]:
                transport_type = get_value_from_documentid(
                    transaction_executor, Constants.CONTAINER_TABLE_NAME,
                    container_id, "TransportType")
                print(transport_type)
                if transport_type[0] == 1:
                    airway_bills = get_value_from_documentid(
                        transaction_executor, Constants.CONTAINER_TABLE_NAME,
                        container_id, "AirwayBillIds")
                    update_document(transaction_executor,
                                    Constants.AIRWAY_BILL_TABLE_NAME,
                                    "RecieverScEntityId", airway_bills[0][-1],
                                    new_truck_carrier_id)
                    pick_up_location = get_value_from_documentid(
                        transaction_executor, Constants.AIRWAY_BILL_TABLE_NAME,
                        airway_bills[0][-1], "ImportAirportName")
                else:
                    bill_of_lading = get_value_from_documentid(
                        transaction_executor, Constants.CONTAINER_TABLE_NAME,
                        container_id, "BillOfLadingIds")
                    update_document(transaction_executor,
                                    Constants.BILL_OF_LADING_TABLE_NAME,
                                    "RecieverScEntityId",
                                    bill_of_lading[0][-1],
                                    new_truck_carrier_id)
                    pick_up_location = get_value_from_documentid(
                        transaction_executor,
                        Constants.BILL_OF_LADING_TABLE_NAME,
                        bill_of_lading[0][-1], "ImportPortName")
                delivery_location = get_scentity_contact(
                    transaction_executor, actual_sc_entity_id, "Address")
                consignee_name = get_value_from_documentid(
                    transaction_executor, Constants.SCENTITY_TABLE_NAME,
                    actual_sc_entity_id, "ScEntityName")
                lorry_reciept_id = create_lorry_reciept(
                    transaction_executor, new_truck_carrier_id, "",
                    pick_up_location, delivery_location, actual_sc_entity_id,
                    consignee_name, False)
                update_document_in_container(transaction_executor,
                                             container_id, "LorryRecieptIds",
                                             lorry_reciept_id[0])
                pick_up_request_id = create_pick_up_request(
                    transaction_executor, actual_sc_entity_id,
                    new_truck_carrier_id, purchase_order_id, "3")

                # logger.info("New Request was made!")
                return pick_up_request_id[0]

        else:
            raise Exception("Not Authorized!!")
    else:
        raise Exception("Document does not exist!")