Пример #1
0
def assign_cases_into_pallete(transaction_executor, case_ids, product_code):
    number_of_palletes_required = int(
        len(case_ids) / Constants.CASES_PER_PALLETE)
    starting_case_number = 0
    ending_case_number = int(Constants.CASES_PER_PALLETE)
    palletes = []
    for pallete in range(1, number_of_palletes_required + 1):
        s_no = get_index_number(transaction_executor,
                                Constants.PALLETE_TABLE_NAME, "PalleteNumber")
        pallete_number = "2" + str(product_code) + str(
            s_no)  #<<-----------level 2 denotes pallete level of product
        current_case_ids = case_ids[starting_case_number:ending_case_number]
        pallete = {
            "PalleteNumber": pallete_number,
            "CaseIds": current_case_ids,
            "ContainerId": ""
        }
        pallete_id = insert_documents(transaction_executor,
                                      Constants.PALLETE_TABLE_NAME,
                                      convert_object_to_ion(pallete))
        palletes.append(pallete_id[0])
        starting_case_number = starting_case_number + Constants.CASES_PER_PALLETE
        ending_case_number = starting_case_number + Constants.CASES_PER_PALLETE
        update_pallete_ids_in_cases(transaction_executor, current_case_ids,
                                    pallete_id)

    return palletes
Пример #2
0
def generate_inventory(transaction_executor, product_id, batch):

    if batch_table_exist(transaction_executor, product_id):
        BatchTableId = batch_table_exist(transaction_executor, product_id)
        # logger.info("Batch Table Found : {}!".format(BatchTableId))
    else:
        BatchTableId = create_batch_table(transaction_executor, product_id)
        # logger.info("Batch Table was created with the id: {}".format(BatchTableId))
        update_BatchTableId(transaction_executor, product_id, BatchTableId)

    # get table name from table_id
    batch_table_name = get_tableName_from_tableId(transaction_executor,
                                                  BatchTableId)
    batch_num = get_index_number(transaction_executor, batch_table_name,
                                 "BatchNo")
    # print("batch number is {}".format(batch_num))
    batch['BatchNo'] = batch_num
    batch['UnitsProduced'] = len(batch["ProductInstances"])
    batch['UnitsRemaining'] = int(batch['UnitsProduced'])
    # print(batch)
    statement = 'INSERT INTO {} ?'.format(batch_table_name)
    cursor = transaction_executor.execute_statement(
        statement, convert_object_to_ion(batch))

    try:
        next(cursor)
        # logger.info(" Vaccine Inventory was added.")
    except StopIteration:
        raise Exception("Problem in generating Inventory.")
Пример #3
0
def product_exist(transaction_executor, ProductCode):

    query = 'SELECT * FROM Products as pr WHERE pr.ProductCode = ?'
    cursor1 = transaction_executor.execute_statement(
        query, convert_object_to_ion(ProductCode))
    try:
        next(cursor1)
        # logger.info("Product with produce_code : {} has already been registered or in process of registeration".format(ProductCode))
        return True
    except:
        return False
Пример #4
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
Пример #5
0
def insert_documents(transaction_executor, table_name, documents):
    """
    Insert the given list of documents into a table in a single transaction.
    :type transaction_executor: :py:class:`pyqldb.execution.executor.Executor`
    :param transaction_executor: An Executor object allowing for execution of statements within a transaction.
    :type table_name: str
    :param table_name: Name of the table to insert documents into.
    :type documents: list
    :param documents: List of documents to insert.
    :rtype: list
    :return: List of documents IDs for the newly inserted documents.
    """
    # logger.info('Inserting some documents in the {} table...'.format(table_name))
    statement = 'INSERT INTO {} ?'.format(table_name)
    cursor = transaction_executor.execute_statement(statement, convert_object_to_ion(documents))
    list_of_document_ids = get_document_ids_from_dml_results(cursor)
    
    return list_of_document_ids
Пример #6
0
def generate_new_product_inventory(transaction_executor, inventory_table_name,
                                   product_id, product_instances, case_ids,
                                   pallete_ids, container_ids,
                                   delivered_product_quantity):
    inventory = {
        "ProductId": product_id,
        "ProductInstances": product_instances,
        "CaseIds": case_ids,
        "PalleteIds": pallete_ids,
        "ContainerIds": container_ids,
        "CurrentInventory": delivered_product_quantity,
        "MinimumSellingAmount": "",
        "ProductPrice": ""
    }

    inventory_id = insert_documents(transaction_executor, inventory_table_name,
                                    convert_object_to_ion(inventory))
    return inventory_id
Пример #7
0
def person_already_exists(transaction_executor, employee_id):
    """
    Verify whether a driver already exists in the database.
    :type transaction_executor: :py:class:`pyqldb.execution.executor.Executor`
    :param transaction_executor: An Executor object allowing for execution of statements within a transaction.
    :type gov_id: str
    :param gov_id: The government ID to search `Person` table against.
    :rtype: bool
    :return: If the Person has been registered.
    """
    query = 'SELECT * FROM Persons AS p WHERE p.EmployeeId = ?'
    cursor = transaction_executor.execute_statement(
        query, convert_object_to_ion(employee_id))
    try:
        next(cursor)
        return True
    except StopIteration:
        # logger.info("Person not found.")
        return False
Пример #8
0
def create_invoice(transaction_executor, purchase_order_input):
    invoice_number = get_index_number(transaction_executor,
                                      Constants.INVOICE_TABLE_NAME,
                                      "InvoiceNumber")
    invoice = {
        "InvoiceNumber": "{}".format(invoice_number),
        "ProductId": purchase_order_input["ProductId"],
        "OrderQuantity": purchase_order_input["OrderQuantity"],
        "OrderValue": purchase_order_input["OrderValue"],
        "Approval": {
            "ApproverId": "",
            "isInvoiceApprovedForPayment": False
        },
        "isInvoicePayed": False,
        "TimeOfInvoiceGeneration": datetime.datetime.now().timestamp()
    }

    invoice_id = insert_documents(transaction_executor,
                                  Constants.INVOICE_TABLE_NAME,
                                  convert_object_to_ion(invoice))
    # logger.info("Invoice was created with invoice id {}".format(invoice_id[0]))
    return invoice_id[0]
Пример #9
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
Пример #10
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
Пример #11
0
def create_lorry_reciept(transaction_executor,carrier_id,truck_carrier_person_id,pick_up_location,delivery_location,consignee_id,consignee_name, is_Picked_Up):
    lrno = get_index_number(transaction_executor,Constants.LORRY_RECEIPT_TABLE_NAME,Constants.LORRY_RECEIPT_INDEX_NAME)
    lorry_reciept = {
        "LorryRecieptNumber": lrno ,
        "CarrierId":carrier_id,
        "TruckerId":truck_carrier_person_id,
        "ConsigneeId":consignee_id,
        "ConsigneeName": consignee_name,
        "PickUpLocation":pick_up_location,
        "DeliveryLocation":delivery_location,
        "PickUpTime": datetime.datetime.now().timestamp(),
        "DeliveryTime": "",
        "isPickedUp":is_Picked_Up,
        "isDeliveryDone":False
    }   

    lorry_reciept_id = insert_documents(transaction_executor, Constants.LORRY_RECEIPT_TABLE_NAME,convert_object_to_ion(lorry_reciept))
    # logger.info("LR created: {}!".format(lorry_reciept_id))
    return lorry_reciept_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!")
Пример #13
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!")
Пример #14
0
def assign_palletes_into_container(transaction_executor, pallete_ids,
                                   product_code, purchase_order_id,
                                   carrier_company_id,
                                   certificate_of_origin_id,
                                   products_per_container, transport_type):
    number_of_containers_required = int(
        len(pallete_ids) / Constants.PALLETS_PER_CONTAINER)
    starting_pallete_number = 0
    ending_pallete_number = int(Constants.PALLETS_PER_CONTAINER)
    '''
    here we are creating containers
    in actual scneario container will already be created with iot mapped on them by the SUPERADMIN
    '''

    containers = []
    for container in range(1, number_of_containers_required + 1):
        s_no = get_index_number(transaction_executor,
                                Constants.CONTAINER_TABLE_NAME,
                                "ContainerNumber")
        container_number = "3" + str(product_code) + str(
            s_no)  #<<-----------level 3 denotes container level of product
        current_pallete_ids = pallete_ids[
            starting_pallete_number:ending_pallete_number]
        packing_list_id = create_packing_list(transaction_executor,
                                              products_per_container,
                                              product_code,
                                              current_pallete_ids)
        '''
        Here we are marking container safe when it is generated. In production we will need another file "mark_contaier_safe"
        Manufacturer person will fire this function --> it will fire check_container_safe to check from data of every iot if container is safe.
        '''

        container = {
            "ContainerNumber": container_number,
            "PurchaseOrderIds": purchase_order_id,
            "PalleteIds": current_pallete_ids,
            "ContainerSafety": {
                "isContainerSafeForDelivery": True,
                "LastCheckedAt": datetime.datetime.now().timestamp()
            },
            "CarrierCompanyId":
            carrier_company_id,  ## this carrier is the company which takes in charge of complete frieght of the container that manufacturer chooses
            "TransportType":
            transport_type,  #<<-------- 1 denotes air and 2 denotes ocean
            "PackingListId": packing_list_id,
            "LorryRecieptIds": [],
            "IotIds": [],
            "AirwayBillIds": [],
            "BillOfLadingIds": [],
            "CertificateOfOriginId": certificate_of_origin_id,
            "isPicked": False,
            "isDelivered": False
        }
        container_id = insert_documents(transaction_executor,
                                        Constants.CONTAINER_TABLE_NAME,
                                        convert_object_to_ion(container))
        containers.append(container_id[0])
        starting_pallete_number = starting_pallete_number + Constants.PALLETS_PER_CONTAINER
        ending_pallete_number = starting_pallete_number + Constants.PALLETS_PER_CONTAINER
        update_container_ids_in_palletes(transaction_executor,
                                         current_pallete_ids, container_id)

    return containers