def accept_order(transaction_executor, purchase_order_id, person_id):
    if document_exist(transaction_executor,
                      Constants.PURCHASE_ORDER_TABLE_NAME, purchase_order_id):
        if order_already_accepted(transaction_executor, purchase_order_id):
            raise Exception("Order Already Accepted!")
        else:
            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("Matched!")
                purchase_order_input = create_purchase_order_input(
                    transaction_executor, purchase_order_id,
                    actual_scentity_id)
                invoice_id = create_invoice(transaction_executor,
                                            purchase_order_input)

                update_statement = "UPDATE {} AS po BY id SET po.InvoiceId = '{}' WHERE id = ?".format(
                    Constants.PURCHASE_ORDER_TABLE_NAME, invoice_id)
                cursor = transaction_executor.execute_statement(
                    update_statement, purchase_order_id)

                update_document(transaction_executor,
                                Constants.PURCHASE_ORDER_TABLE_NAME,
                                "Acceptor.isOrderAccepted", purchase_order_id,
                                True)
                update_document(transaction_executor,
                                Constants.PURCHASE_ORDER_TABLE_NAME,
                                "Acceptor.ApprovingPersonId",
                                purchase_order_id, person_id)
                try:
                    next(cursor)
                    logger.info(
                        " ================================== O R D E R =========== A C C E P T E D ==============================="
                    )
                    # logger.info("Invoice is updated!")
                    return invoice_id
                except StopIteration:
                    raise Exception("Problem updating invoice")
            else:
                raise Exception("You are not authorized to accept this order.")
    else:
        raise Exception("Trouble finding Purchase Order!")
Example #2
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!")
Example #3
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=========")
Example #4
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)
def update_price_and_minimum_selling_amount(transaction_executor, product_id,
                                            minimum_selling_amount,
                                            new_product_price,
                                            distributor_person_id):
    # check if person has scentity
    actual_sc_entity_id = get_scentityid_from_personid(transaction_executor,
                                                       distributor_person_id)
    if actual_sc_entity_id:
        # check if sc entity has inventory table and product_id
        inventory_table = inventory_table_already_exist(
            transaction_executor, actual_sc_entity_id)
        if inventory_table:
            #check product exist with distributor
            if product_exist_in_inventory(transaction_executor,
                                          inventory_table[0], product_id):
                ## minimum selling amount is in number of cases
                inventory_id = next(
                    get_document_ids(transaction_executor, inventory_table[0],
                                     "ProductId", product_id))
                print(inventory_id)
                update_document(transaction_executor, inventory_table[0],
                                "ProductPrice", inventory_id,
                                new_product_price)
                update_document(transaction_executor, inventory_table[0],
                                "MinimumSellingAmount", inventory_id,
                                minimum_selling_amount)

                logger.info(
                    "=================== P R I C E === A N D ==== S E L L I N G ++++ A M O U N T ======= U P D A T E D ========"
                )

            else:
                raise Exception("Product does not exist in inventory!")
        else:
            raise Exception("No inventory table exist")
    else:
        raise Exception("No SCentity for the person")
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))
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!")
Example #8
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.")
Example #9
0
def update_pallete_ids_in_cases(transaction_executor, case_ids, pallete_id):
    for case_id in case_ids:
        update_document(transaction_executor, Constants.CASES_TABLE_NAME,
                        "PalleteId", case_id, pallete_id)
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")
Example #11
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!")
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")
Example #13
0
def update_container_ids_in_palletes(transaction_executor, pallete_ids,
                                     container_id):
    for pallete_id in pallete_ids:
        update_document(transaction_executor, Constants.PALLETE_TABLE_NAME,
                        "ContainerId", pallete_id, container_id)
Example #14
0
def update_container_ids_in_purchase_order(transaction_executor, container_ids,
                                           purchase_order_id):
    update_document(transaction_executor, Constants.PURCHASE_ORDER_TABLE_NAME,
                    "HighestPackagingLevelIds", purchase_order_id,
                    container_ids)
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!")
Example #16
0
def assign_products_into_case(transaction_executor, product_id,
                              batch_table_name, product_units_ordered,
                              products_per_case, purchase_order_id,
                              product_code):

    statement = 'SELECT * FROM {} as b By id where b.UnitsRemaining > 0'.format(
        batch_table_name)
    cursor = transaction_executor.execute_statement(statement)
    total_number_of_cases_required = int(product_units_ordered /
                                         products_per_case)
    current_number_of_cases_required = int(product_units_ordered /
                                           products_per_case)
    cases = []
    for batch in cursor:
        if current_number_of_cases_required > 0:
            current_batch = dumps(batch, binary=False)
            current_batch = current_batch[9:]
            current_batch = current_batch.replace('"', '').replace(
                '{', '{"').replace('}', '"}').replace(':', '":"').replace(
                    ',', '","').replace('[', '["').replace(']', '"]').replace(
                        '"[', '[').replace(']"', ']')
            current_batch_dict = ast.literal_eval(current_batch)
            # print(current_batch_dict)

            batch_inventory_left = current_batch_dict['UnitsRemaining']
            batch_inventory_left = int(batch_inventory_left)

            # logger.info("current batch_inventory: {} ".format(batch_inventory_left))
            # logger.info("{} cases will be filled for this order!".format(current_number_of_cases_required))

            product_instances = current_batch_dict[
                'ProductInstances']  # change with 'ProductInstances'
            batch_id = current_batch_dict['id']
            # logger.info("Filling a case from batch {}".format(batch_id))
            units_produced = int(current_batch_dict['UnitsProduced'])
            starting_case_number = len(cases)
            ending_case_number = len(cases)
            for case in range(
                    len(cases) + 1,
                    int(total_number_of_cases_required) + 1):
                if batch_inventory_left > 0:
                    case_product_instances = product_instances[(
                        units_produced -
                        batch_inventory_left):(units_produced +
                                               int(products_per_case) -
                                               batch_inventory_left)]
                    logger.info(case_product_instances)
                    case_id = create_case(transaction_executor,
                                          product_code[0], purchase_order_id,
                                          case_product_instances,
                                          products_per_case)
                    logger.info(
                        "--------------------------------Case {} added----------------------------------"
                        .format(case))
                    cases.append(case_id[0])
                    batch_inventory_left = batch_inventory_left - products_per_case
                    current_number_of_cases_required = current_number_of_cases_required - 1
                    ending_case_number = ending_case_number + 1
                    if current_number_of_cases_required == 0:
                        update_document(transaction_executor, batch_table_name,
                                        "UnitsRemaining", batch_id,
                                        int(batch_inventory_left))
                        insert_caseIds(
                            transaction_executor, batch_table_name, batch_id,
                            cases[starting_case_number:ending_case_number])
                        # update_document(transaction_executor,batch_table_name,"CaseIds",batch_id,cases[starting_case_number:ending_case_number])
                else:
                    update_document(transaction_executor, batch_table_name,
                                    "UnitsRemaining", batch_id,
                                    int(batch_inventory_left))
                    insert_caseIds(
                        transaction_executor, batch_table_name, batch_id,
                        cases[starting_case_number:ending_case_number])
                    #update_document(transaction_executor,batch_table_name,"CaseIds",batch_id,cases[starting_case_number:ending_case_number])
                    # logger.info("No inventory left! Moving to next batch to fill {} more cases".format(current_number_of_cases_required))
                    break
        else:
            break

    # logger.info("All the cases packed :{}".format(cases))
    return cases
Example #17
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")
Example #18
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")
Example #19
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.")