Ejemplo n.º 1
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
Ejemplo n.º 2
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
Ejemplo n.º 3
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
Ejemplo n.º 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
Ejemplo n.º 5
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
Ejemplo n.º 6
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
Ejemplo n.º 7
0
def create_iot(transaction_executor,person_id, iot):
    if person_is_superadmin(transaction_executor,person_id):
        iot_number = get_index_number(transaction_executor,Constants.IOT_TABLE_NAME,"IoTNumber")
        iot.update({"IoTNumber": iot_number})
        iot_type = iot['IoTType']
        if iot_type ==1:
            iot_name = "Temperature Sensor"
        elif iot_type == 2:
            iot_name = "Humidity Sensor"
        elif iot_type == 3:
            iot_name = "Location Sensor"
        else:
            iot_name = "UnkownSensor"
        
        iot.update({"IoTName":iot_name})
        iot_id = insert_documents(transaction_executor,Constants.IOT_TABLE_NAME, [iot])
        logger.info(" ================== I O T ======= O N B O A R D E D ====================")
        return iot_id [0]
    else:
        raise Exception("You are not a Super admin")
Ejemplo n.º 8
0
def register_product(transaction_executor, product, person_id):
    ## check if the vaccine with GTIN already exist
    # scentity_id = get_scentityid_from_personid(transaction_executor,person_id)

    logger.info("Person_id: {}".format(person_id))
    actual_scentity_id = get_scentityid_from_personid(transaction_executor,
                                                      person_id)
    if actual_scentity_id:
        product.update({'ManufacturerId': actual_scentity_id})
        # logger.info("Matched for authorization!")
        if get_document_superadmin_approval_status(
                transaction_executor, Constants.SCENTITY_TABLE_NAME,
                actual_scentity_id):
            logger.info("Entity is Approved to register product!")
            ProductCode = product["ProductCode"]
            if product_exist(transaction_executor, ProductCode):
                raise Exception(" Product already exists.")
            else:
                if check_products_per_container_and_selling_amount(
                        transaction_executor, product):
                    result = insert_documents(transaction_executor,
                                              Constants.PRODUCT_TABLE_NAME,
                                              [product])
                    product_id = result[0]
                    product_request_id = create_mcg_request(
                        transaction_executor, product_id, person_id, 2)
                    # logger.info("Request was created for product Id : {} with product request id {}".format(product_id, product_request_id))
                    logger.info(
                        " ================================== P R O D U C T =========== R E G I S T R A T I O N ========== B E G A N====================="
                    )
                    return product_id, product_request_id
                else:
                    cases_per_container = Constants.PALLETS_PER_CONTAINER * Constants.CASES_PER_PALLETE
                    raise Exception(
                        "Invalid ProductsPerContainer! Make it multple of : {}"
                        .format(cases_per_container))
        else:
            raise Exception(
                "Entity not approved yet. Cannot register the product")
    else:
        raise Exception("You don't belong to any entity")
Ejemplo n.º 9
0
def create_packing_list(transaction_executor, products_per_container,
                        product_code, palleteIds):
    container_case_ids = []
    # print("pallete ids are : {}".format(palleteIds))
    for palleteId in palleteIds:
        pallete_case_ids = get_value_from_documentid(
            transaction_executor, Constants.PALLETE_TABLE_NAME, palleteId,
            "CaseIds")
        container_case_ids.append(pallete_case_ids[0])

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

    packing_list_id = insert_documents(transaction_executor,
                                       Constants.PACKING_LIST_TABLE_NAME,
                                       packing_list)
    return packing_list_id[0]
Ejemplo n.º 10
0
def create_req_to_join_scentity(transaction_executor, sc_entity, employee_id,
                                person_id):
    request_number = get_index_number(transaction_executor,
                                      Constants.JOINING_REQUEST_TABLE_NAME,
                                      Constants.JOINING_REQUESTID_INDEX_NAME)
    sc_entity_identification_code = sc_entity['ScEntityIdentificationCode']
    sc_entity_id = next(
        get_document_ids(transaction_executor, Constants.SCENTITY_TABLE_NAME,
                         "ScEntityIdentificationCode",
                         sc_entity_identification_code))
    request = {
        "JoiningRequestNumber": request_number,
        "SenderEmployeeId": employee_id,
        "SenderPersonId": person_id,
        "ScEntityId": sc_entity_id,
        "isAccepted": False
    }
    print(request)

    result = insert_documents(transaction_executor,
                              Constants.JOINING_REQUEST_TABLE_NAME, [request])
    return result[0]
Ejemplo n.º 11
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]
Ejemplo n.º 12
0
def create_mcg_request(transaction_executor, document_id, person_id,
                       request_type):
    request_number = get_index_number(transaction_executor,
                                      Constants.SUPERADMIN_REQUEST_TABLE_NAME,
                                      Constants.SUPERADMIN_REQUEST_INDEX_NAME)
    request = {
        "McgRequestNumber": request_number,
        "DocumentId": document_id,
        "RequestType": request_type,
        "SenderPersonId": person_id,
        "isAccepted": False
    }

    # request type is 1 for company 2 for product
    if mcg_request_already_sent(transaction_executor, document_id):
        raise Exception(
            "Request already sent for document id : {}".format(document_id))
    else:
        result = insert_documents(transaction_executor,
                                  Constants.SUPERADMIN_REQUEST_TABLE_NAME,
                                  [request])
        request_id = result[0]
        return request_id
Ejemplo n.º 13
0
def create_pick_up_request(transaction_executor, requestor_sc_entity_id,
                           carrier_company_id, purchase_order_id,
                           transport_type):
    request_number = get_index_number(transaction_executor,
                                      Constants.PICK_UP_REQUESTS_TABLE,
                                      Constants.PICK_UP_REQUESTS_INDEX_NAME)
    pick_up_location = get_scentity_contact(transaction_executor,
                                            requestor_sc_entity_id, "Address")
    pick_up_request = {
        "PickUpRequestNumber": request_number,
        "PickUpLocation": pick_up_location,
        "RequestorId": requestor_sc_entity_id,
        "CarrierCompanyId": carrier_company_id,
        "PurchaseOrderId": purchase_order_id,
        "isAccepted": False,
        "TransportType": transport_type
    }

    pick_up_request_id = insert_documents(transaction_executor,
                                          Constants.PICK_UP_REQUESTS_TABLE,
                                          pick_up_request)
    # logger.info("pick_up_request was created :{}".format(pick_up_request_id))
    return pick_up_request_id
Ejemplo n.º 14
0
def register_new_Person(transaction_executor, person):
    """
    Register a new driver in QLDB if not already registered.
    :type transaction_executor: :py:class:`pyqldb.execution.executor.Executor`
    :param transaction_executor: An Executor object allowing for execution of statements within a transaction.
    :type driver: dict
    :param driver: The driver's license to register.
    """
    employee_id = person['EmployeeId']
    if person_already_exists(transaction_executor, employee_id):
        result = next(
            get_document_ids(transaction_executor, Constants.PERSON_TABLE_NAME,
                             'EmployeeId', employee_id))
        # logger.info('Person with  employee_Id {} already exists with PersonId: {} .'.format(employee_id, result))
    else:
        person.update({"isSuperAdmin":
                       False})  #<<-----------uncomment after onboarding admin
        person.update({"isAdmin": False
                       })  #<<----------- un comment after onboarding admin
        result = insert_documents(transaction_executor,
                                  Constants.PERSON_TABLE_NAME, [person])
        result = result[0]
        # logger.info("New Person registered with person id : {}".format(result))
    return result
Ejemplo n.º 15
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
Ejemplo n.º 16
0
def register_new_user_with_scentity(transaction_executor, person,
                                    new_sc_entity):
    """
    Register a new driver and a new driver's license 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 driver: dict
    :param driver: The driver's license to register.
    :type new_license: dict
    :param new_license: The driver's license to register.
    """
    person_id = register_new_Person(transaction_executor, person)
    if get_scentityid_from_personid(transaction_executor, person_id):
        raise Exception(
            "Person with personId '{}' already belongs to a SC Entity".format(
                person_id))
    else:
        # logger.info("Registering new Person's entity...")
        if lookup_scentity(transaction_executor, new_sc_entity):
            # send request to join a new entity
            # logger.info(' Entity already exist. Sending request to join it.')
            employee_id = person['EmployeeId']
            scentity_id_code = new_sc_entity['ScEntityIdentificationCode']
            scentity_id = next(
                get_document_ids(transaction_executor,
                                 Constants.SCENTITY_TABLE_NAME,
                                 'ScEntityIdentificationCode',
                                 scentity_id_code))

            if get_document_superadmin_approval_status(
                    transaction_executor, Constants.SCENTITY_TABLE_NAME,
                    scentity_id):
                if req_already_sent(transaction_executor, person_id) == True:
                    raise Exception(
                        "Please wait for your company admin to approve the request."
                    )
                else:
                    joining_request_id = create_req_to_join_scentity(
                        transaction_executor, new_sc_entity, employee_id,
                        person_id)
                    send_request_to_company(transaction_executor,
                                            joining_request_id, new_sc_entity)
                    return person_id, joining_request_id
            else:
                raise Exception('Wait for MCG to approve this entity ... ')
        else:
            #create a new entity
            if req_already_sent(transaction_executor, person_id) == True:
                raise Exception(
                    "Please wait for your company admin to approve the request."
                )
            else:
                update_person_to_admin(transaction_executor, person_id)
                new_sc_entity.update({'PersonIds': [str(person_id)]})
                new_sc_entity.update({'isApprovedBySuperAdmin': False})
                try:
                    result = insert_documents(transaction_executor,
                                              Constants.SCENTITY_TABLE_NAME,
                                              [new_sc_entity])
                    sc_entity_id = result[0]

                    mcg_request_id = create_mcg_request(
                        transaction_executor, sc_entity_id, person_id, 1)

                    sc_entity_id_code = new_sc_entity[
                        "ScEntityIdentificationCode"]
                    # logger.info('Registration process began for new SCEntity with ScEntityIdentificationCode : {} and ScEntityId: {}. A new request was create for super admin : {}'.format(sc_entity_id_code,sc_entity_id, mcg_request_id))
                    logger.info(
                        " ================= P E R S O N ======= A N D ===== S C E N T I T Y ========= R E G I S T R A T I O N ========= I N I T I A T E D========="
                    )
                    return person_id, sc_entity_id, mcg_request_id
                except StopIteration:
                    raise Exception(
                        'Problem occurred while inserting Scentity, please review the results.'
                    )
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!")
Ejemplo n.º 18
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!")