def create_assignments(assignments_in_csv, workforce_project,
                       assignment_types_dict, dispatchers_dict, workers_dict):
    '''add assignments to workforce project
    :param assignments in csv: list of dictionaries of each record in feature fservice
    :param workforce_project: workforce project defined in define_project
    :param assignment_type_dict: assignment types dict defined in define_project
    :param dispatchers_dict: dispatchers dictionary defined in define_project
    :param workers_dict: workers dictionary defined in define_project'''

    assignments_to_add = []
    for assignment in assignments_in_csv:
        print(f"assignment: {assignment}")
        assignment_to_add = workforce.Assignment(workforce_project)
        # Create the geometry
        geometry = dict(x=float(assignment['x']),
                        y=float(assignment['y']),
                        spatialReference=dict(wkid=int(4326)))
        print(geometry)
        assignment_to_add.geometry = geometry

        fs_assignment_type = assignment['type_of_issue']
        assignment_to_add.assignment_type = assignment_types_dict[
            fs_assignment_type]
        print(f"Added type {fs_assignment_type}")

        assignment_to_add.location = assignment['address']
        print("Added address")

        assignment_to_add.description = assignment['add_details']
        print("Added details")

        assignment_to_add.priority = "High"

        #Set dispatcher
        (k, v), = dispatchers_dict.items()
        assignment_to_add.dispatcher = dispatchers_dict[k]

        #set worker and assign
        (k, v), workers_dict.items()
        assignment_to_add.worker = workers_dict[k]
        assignment_to_add.status = "assigned"

        #add date
        assignment_to_add.assigned_date = datetime.datetime.utcnow()

        # Add all assignments to the list created
        assignments_to_add.append(assignment_to_add)

        #load assignments
        assignments = workforce_project.assignments.batch_add(
            assignments_to_add)

    print("created new assignment")
Exemplo n.º 2
0
def main(arguments):  # noqa: C901
    # initialize logging
    logger = initialize_logging(arguments.log_file)

    # Create the GIS
    logger.info("Authenticating...")

    # First step is to get authenticate and get a valid token
    gis = GIS(arguments.org_url,
              username=arguments.username,
              password=arguments.password,
              verify_cert=not arguments.skip_ssl_verification)

    # Get the project and data
    item = gis.content.get(arguments.project_id)
    project = workforce.Project(item)
    dispatcher = project.dispatchers.search(where="{}='{}'".format(
        project._dispatcher_schema.user_id, arguments.username))
    if not dispatcher:
        log_critical_and_raise_exception("{} is not a dispatcher".format(
            args.username))

    # Read the csv file
    logger.info("Reading CSV file: {}...".format(arguments.csv_file))
    assignments_in_csv = []
    locations = []
    with open(arguments.csv_file, 'r') as file:
        reader = csv.DictReader(file)
        for row in reader:
            locations.append(row[args.location_field])
            assignments_in_csv.append(row)

    # Fetch assignment types
    assignment_types = project.assignment_types.search()
    assignment_type_dict = {}
    for assignment_type in assignment_types:
        assignment_type_dict[assignment_type.name] = assignment_type

    # Fetch dispatchers
    dispatchers = project.dispatchers.search()
    dispatchers_dict = {}
    for dispatcher in dispatchers:
        dispatchers_dict[dispatcher.user_id] = dispatcher

    # Fetch the workers
    workers = project.workers.search()
    workers_dict = {}
    for worker in workers:
        workers_dict[worker.user_id] = worker

    if not (args.x_field and args.y_field):
        geocoder = None
        if args.custom_geocoder:
            geocoder = Geocoder.fromitem(gis.content.get(args.custom_geocoder))
        addresses = batch_geocode(locations,
                                  geocoder=geocoder,
                                  out_sr=args.wkid)
    assignments_to_add = []
    for i, assignment in enumerate(assignments_in_csv):
        assignment_to_add = workforce.Assignment(
            project,
            assignment_type=assignment_type_dict[assignment[
                args.assignment_type_field]],
            status="unassigned")

        # Create the geometry
        if args.x_field and args.y_field:
            geometry = dict(x=float(assignment[args.x_field]),
                            y=float(assignment[args.y_field]),
                            spatialReference=dict(wkid=int(args.wkid)))
        else:
            try:
                location_geometry = addresses[i]['location']
            except Exception as e:
                logger.info(e)
                logger.info(
                    "Geocoding did not work for the assignment with location {}. "
                    "Please check your addresses again".format(
                        assignment[args.location_field]))
                logger.info("Continuing on to the next assignment")
                continue
            location_geometry['spatialReference'] = dict(wkid=int(args.wkid))
            geometry = location_geometry
        assignment_to_add.geometry = geometry

        # Determine the assignment due date, and if no time is provided, make the due date all day
        if args.due_date_field and assignment[args.due_date_field]:
            d = datetime.datetime.strptime(assignment[args.due_date_field],
                                           args.date_format)
            p_date = pendulum.instance(d, tz=args.timezone)
            if p_date.second == 0 and p_date.hour == 0 and p_date.minute == 0:
                p_date = p_date.at(hour=23, minute=59, second=59)
            # Convert date to UTC time
            assignment_to_add.due_date = datetime.datetime.fromtimestamp(
                p_date.in_tz('UTC').timestamp())

        # Set the location
        assignment_to_add.location = assignment[args.location_field]

        # Set the dispatcher
        if args.dispatcher_field and assignment[args.dispatcher_field]:
            assignment_to_add.dispatcher = dispatchers_dict[assignment[
                args.dispatcher_field]]
        else:
            assignment_to_add.dispatcher = dispatcher

        # Fetch workers and assign the worker to the assignment
        if args.worker_field and assignment[args.worker_field]:
            assignment_to_add.worker = workers_dict[assignment[
                args.worker_field]]
            assignment_to_add.assigned_date = datetime.datetime.fromtimestamp(
                pendulum.now('UTC').timestamp())
            assignment_to_add.status = "assigned"
        else:
            assignment_to_add.status = "unassigned"

        # Set the priority
        if args.priority_field and assignment[args.priority_field]:
            assignment_to_add.priority = assignment[args.priority_field]

        # Set the description
        if args.description_field and assignment[args.description_field]:
            assignment_to_add.description = assignment[args.description_field]

        # Set the work order id
        if args.work_order_id_field and assignment[args.work_order_id_field]:
            assignment_to_add.work_order_id = assignment[
                args.work_order_id_field]

        # Set attachment
        if args.attachment_file_field and assignment[
                args.attachment_file_field]:
            assignment_to_add.attachment_file = types.SimpleNamespace()
            assignment_to_add.attachment_file = assignment[
                args.attachment_file_field]

        # Add all assignments to the list created
        assignments_to_add.append(assignment_to_add)

    # Batch add all assignments to the project
    logger.info("Adding Assignments...")
    assignments = project.assignments.batch_add(assignments_to_add)
    logger.info("Adding Attachments...")
    for assignment in assignments:
        if hasattr(assignment, "attachment_file"):
            assignment.attachments.add(assignment.attachment_file)
    logger.info("Completed")
    def main(arguments):
        # initialize logging
        logger = initialize_logging(arguments.log_file)
        # Create the GIS
        logger.info("Authenticating...")
        # First step is to get authenticate and get a valid token
        gis = GIS(arguments.org_url,
                  username=arguments.username,
                  password=arguments.password,
                  verify_cert=not arguments.skip_ssl_verification)
        # Get the project and data
        item = gis.content.get(arguments.project_id)
        project = workforce.Project(item)
        dispatcher = project.dispatchers.search(
            where="{}='{}'".format(project._dispatcher_schema.user_id, arguments.username))
        if not dispatcher:
            log_critical_and_raise_exception("{} is not a dispatcher".format(args.username))
        # Read the csv file
        logger.info("Reading CSV file: {}...".format(arguments.csv_file))
        assignments_in_csv = []
        with open(arguments.csv_file, 'r') as file:
            reader = csv.DictReader(file)
            for row in reader:
                assignments_in_csv.append(row)
        #########################################
        #GET A LIST OF THE CSV'S WORK_ORDER_IDS##
        #########################################
        assignments_in_csv_workOrderId =[] #creates an empty list to save the order IDs
        for i in assignments_in_csv:
            orderID = i['Work Order Id'] #A work order ID in the CSV file we want to load
            assignments_in_csv_workOrderId.append(orderID) #append the order IDs
        ####################################################
        #GET THE LAST 30 DAYS WORK ORDERS WITHIN WORKFORCE###
        #####################################################

        today = datetime.today() #time stamp at the moment of runnig this script
        thirtyDays_ago = today - timedelta(days=30) #obtain the date and time from 30 days ago

        lastThirtyDays ="{} <= '{}' OR {} >= '{}'"\
            .format(project._track_schema.creation_date, today.strftime("%m/%d/%Y %H:%M:%S"),
                    project._track_schema.creation_date, thirtyDays_ago.strftime("%m/%d/%Y %H:%M:%S"))#create a query of the last 30 days
        assgments = project.assignments.search(where=lastThirtyDays) #list all the assignments within Workforce Web App
        currentOrders = [] #create an empty list where we will save the assignments withing Workforce
        for a in range(0,len(assgments)):
            assgment = assgments[a]
            assgment_orderID = assgment.work_order_id
            currentOrders.append(assgment_orderID)
        ################################################################
        ###COMPARE THE CSV'S ORDER IDs TO THE CURRENT WORKORDER #########
        ###IN WORKFORCE AND GENERATE A LIST OF DUPLICATES###############
        ##############################################################
        duplicates = [] #list containing the CSV's workorder that are identical to those in workforce
        for order in assignments_in_csv_workOrderId:
            for current_o in currentOrders:
                if order == current_o:
                    duplicates.append(order)
        #########################################################
        ##DROP THE DUPLICATES FROM THE ASSIGNMENTS IN THE CSV####
        #########################################################

        for i in reversed(range(len(assignments_in_csv))):
            a = assignments_in_csv[i]
            orderID = a['Work Order Id']
            for h in duplicates:
                if orderID == h:
                    assignments_in_csv.pop(i)

        #############################################################
        #######UPLOAD NON-REPEATED OR INFORM THAT ALL ARE REPEATED###
        #############################################################

        if len(assignments_in_csv) == 0:
            print("The assignments you are trying to upload were previously uploaded. This scrip "
                  "won't run to prevent duplicate work order IDs.")
        elif len(assignments_in_csv) > 0:
            # Fetch assignment types
            assignment_types = project.assignment_types.search()
            assignment_type_dict = {}
            for assignment_type in assignment_types:
                assignment_type_dict[assignment_type.name] = assignment_type

            # Fetch dispatchers
            dispatchers = project.dispatchers.search()
            dispatchers_dict = {}
            for dispatcher in dispatchers:
                dispatchers_dict[dispatcher.user_id] = dispatcher

            # Fetch the workers
            workers = project.workers.search()
            workers_dict = {}
            for worker in workers:
                workers_dict[worker.user_id] = worker

            # assignments to add
            assignments_to_add = []
            for assignment in assignments_in_csv:
                assignment_to_add = workforce.Assignment(project,
                                                         assignment_type=assignment_type_dict[
                                                             assignment[args.assignment_type_field]],
                                                         )

                # Create the geometry
                geometry = dict(x=float(assignment[args.x_field]),
                                y=float(assignment[args.y_field]),
                                spatialReference=dict(
                                    wkid=int(args.wkid)))
                assignment_to_add.geometry = geometry

                # Determine the assignment due date, and if no time is provided, make the due date all day
                if args.due_date_field and assignment[args.due_date_field]:
                    d = arrow.Arrow.strptime(assignment[args.due_date_field], args.date_format).replace(
                        tzinfo=dateutil.tz.gettz(args.timezone))
                    if d.datetime.second == 0 and d.datetime.hour == 0 and d.datetime.minute == 0:
                        d = d.replace(hour=23, minute=59, second=59)
                    # Convert date to UTC time
                    assignment_to_add.due_date = d.to('utc').datetime

                # Set the location
                assignment_to_add.location = assignment[args.location_field]

                # Set the dispatcher
                if args.dispatcher_field and assignment[args.dispatcher_field]:
                    assignment_to_add.dispatcher = dispatchers_dict[assignment[args.dispatcher_field]]
                else:
                    assignment_to_add.dispatcher = dispatcher

                # Fetch workers and assign the worker to the assignment
                if args.worker_field and assignment[args.worker_field]:
                    assignment_to_add.worker = workers_dict[assignment[args.worker_field]]
                    assignment_to_add.assigned_date = arrow.now().to('utc').datetime
                    assignment_to_add.status = "assigned"
                else:
                    assignment_to_add.status = "unassigned"

                # Set the priority
                if args.priority_field and assignment[args.priority_field]:
                    assignment_to_add.priority = assignment[args.priority_field]

                # Set the description
                if args.description_field and assignment[args.description_field]:
                    assignment_to_add.description = assignment[args.description_field]

                # Set the work order id
                if args.work_order_id_field and assignment[args.work_order_id_field]:
                    assignment_to_add.work_order_id = assignment[args.work_order_id_field]

                # Set attachment
                if args.attachment_file_field and assignment[args.attachment_file_field]:
                    assignment_to_add.attachment_file = types.SimpleNamespace()
                    assignment_to_add.attachment_file = assignment[args.attachment_file_field]

                # Add all assignments to the list created
                assignments_to_add.append(assignment_to_add)

            # Batch add all assignments to the project
            logger.info("Adding Assignments...")
            assignments = project.assignments.batch_add(assignments_to_add) #I NEED TO UNCOMMENT THI TO WORK
            logger.info("Adding Attachments...")
            for assignment in assignments:
                if hasattr(assignment, "attachment_file"):
                    assignment.attachments.add(assignment.attachment_file)
            logger.info("Completed")

            if len(duplicates) == 0:
                print("SUCCESS!!")
            elif len(duplicates) > 0:
                print("This work orders were previously uploaded and they were ignored to prevent duplication:")
                print(duplicates)
                print("The rest of the work orders have been uploaded successfully.")
    proj_Due = selection.features[0].get_value("Due_Date")
    proj_Date = datetime.datetime.fromtimestamp(proj_Due / 1e3)
    proj_Worker = selection.features[0].get_value("Worker")
    proj_Assignment = selection.features[0].get_value("AssignmentType")
    if (proj_Assignment == "new"):
        proj_Type = 1
    elif (proj_Assignment == "update"):
        proj_Type = 2
    else:
        proj_Type = 3
    proj_Location = selection.features[0].get_value(
        "Address_1") + ", " + selection.features[0].get_value(
            "City") + ", " + selection.features[0].get_value(
                "State") + ", " + selection.features[0].get_value("Zip")
    assignments_to_add = []
    assignment_to_add = workforce.Assignment(project)
    geometry = selection.features[0].geometry
    assignment_to_add.geometry = geometry
    assignment_to_add.due_date = proj_Date
    assignment_to_add.assignment_type = proj_Type
    assignment_to_add.location = proj_Location
    assignment_to_add.dispatcher = dispatcher
    assignment_to_add.worker = workers_dict[proj_Worker]
    assignment_to_add.assigned_date = arrow.now().to('utc').datetime
    assignment_to_add.status = "assigned"
    assignments_to_add.append(assignment_to_add)
    assignments = project.assignments.batch_add(assignments_to_add)

elif (choice == "2"):
    datebegin = datetime.datetime.now()
    datebeginstr = str(datebegin.year) + "-" + str(
def main(arguments):
    # initialize logging
    logger = initialize_logging(arguments.log_file)
    # Create the GIS
    logger.info("Authenticating...")
    # First step is to get authenticate and get a valid token
    gis = GIS(arguments.org_url,
              username=arguments.username,
              password=arguments.password,
              verify_cert=not arguments.skip_ssl_verification)
    # Get the project and data
    item = gis.content.get(arguments.project_id)
    project = workforce.Project(item)
    dispatcher = project.dispatchers.search(where="{}='{}'".format(
        project._dispatcher_schema.user_id, arguments.username))
    if not dispatcher:
        log_critical_and_raise_exception("{} is not a dispatcher".format(
            args.username))
    # Read the csv file
    logger.info("Reading CSV file: {}...".format(arguments.csv_file))
    assignments_in_csv = []
    with open(arguments.csv_file, 'r') as file:
        reader = csv.DictReader(file)
        for row in reader:
            assignments_in_csv.append(row)

    # Fetch assignment types
    assignment_types = project.assignment_types.search()
    assignment_type_dict = {}
    for assignment_type in assignment_types:
        assignment_type_dict[assignment_type.name] = assignment_type

    # Fetch dispatchers
    dispatchers = project.dispatchers.search()
    dispatchers_dict = {}
    for dispatcher in dispatchers:
        dispatchers_dict[dispatcher.user_id] = dispatcher

    # Fetch the workers
    workers = project.workers.search()
    workers_dict = {}
    for worker in workers:
        workers_dict[worker.user_id] = worker

    assignments_to_add = []
    for assignment in assignments_in_csv:
        assignment_to_add = workforce.Assignment(
            project,
            assignment_type=assignment_type_dict[assignment[
                args.assignment_type_field]],
        )

        # Create the geometry
        geometry = dict(x=float(assignment[args.x_field]),
                        y=float(assignment[args.y_field]),
                        spatialReference=dict(wkid=int(args.wkid)))
        assignment_to_add.geometry = geometry

        # Determine the assignment due date, and if no time is provided, make the due date all day
        if args.due_date_field and assignment[args.due_date_field]:
            d = arrow.Arrow.strptime(
                assignment[args.due_date_field], args.date_format).replace(
                    tzinfo=dateutil.tz.gettz(args.timezone))
            if d.datetime.second == 0 and d.datetime.hour == 0 and d.datetime.minute == 0:
                d = d.replace(hour=23, minute=59, second=59)
            # Convert date to UTC time
            assignment_to_add.due_date = d.to('utc').datetime

        # Set the location
        assignment_to_add.location = assignment[args.location_field]

        # Set the dispatcher
        if args.dispatcher_field and assignment[args.dispatcher_field]:
            assignment_to_add.dispatcher = dispatchers_dict[assignment[
                args.dispatcher_field]]
        else:
            assignment_to_add.dispatcher = dispatcher

        # Fetch workers and assign the worker to the assignment
        if args.worker_field and assignment[args.worker_field]:
            assignment_to_add.worker = workers_dict[assignment[
                args.worker_field]]
            assignment_to_add.assigned_date = arrow.now().to('utc').datetime
            assignment_to_add.status = "assigned"
        else:
            assignment_to_add.status = "unassigned"

        # Set the priority
        if args.priority_field and assignment[args.priority_field]:
            assignment_to_add.priority = assignment[args.priority_field]

        # Set the description
        if args.description_field and assignment[args.description_field]:
            assignment_to_add.description = assignment[args.description_field]

        # Set the work order id
        if args.work_order_id_field and assignment[args.work_order_id_field]:
            assignment_to_add.work_order_id = assignment[
                args.work_order_id_field]

        # Set attachment
        if args.attachment_file_field and assignment[
                args.attachment_file_field]:
            assignment_to_add.attachment_file = types.SimpleNamespace()
            assignment_to_add.attachment_file = assignment[
                args.attachment_file_field]

        # Add all assignments to the list created
        assignments_to_add.append(assignment_to_add)

    # Batch add all assignments to the project
    logger.info("Adding Assignments...")
    assignments = project.assignments.batch_add(assignments_to_add)
    logger.info("Adding Attachments...")
    for assignment in assignments:
        if hasattr(assignment, "attachment_file"):
            assignment.attachments.add(assignment.attachment_file)
    logger.info("Completed")