forked from Esri/workforce-scripts
-
Notifications
You must be signed in to change notification settings - Fork 0
/
assignment_monitor.py
219 lines (191 loc) · 7.93 KB
/
assignment_monitor.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
# -*- coding: UTF-8 -*-
"""
Copyright 2017 Esri
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
A script to monitor Workforce Assignments for completion.
When an assignment is completed a message is posted to slack
"""
import configparser
import sqlite3
import datetime
import logging
import logging.handlers
import sys
import time
import arcgis
import requests
def post_to_slack(slack_webhook, assignment, project_id):
"""
Posts a message to slack
:param slack_webhook: (string) The url of the slack webhook
:param assignment: (Feature) The feature to use
:return:
"""
# create the message to send
message = "Assignment Completed:\n " \
"Location: {}\n"\
"Description: {}\n" \
"Notes: {}\n"\
"Worker: {}\n"\
"Time: {}\n" \
"Link: {}".format(
assignment.attributes["location"],
assignment.attributes["description"],
assignment.attributes["notes"],
assignment.attributes["Editor"],
datetime.datetime.fromtimestamp(int(assignment.attributes["completedDate"])/1000).strftime("%Y-%m-%d %H:%M"),
"http://workforce.arcgis.com/projects/{}/dispatch/assignments/{}".format(project_id,
assignment.attributes["OBJECTID"])
)
logging.getLogger().info("Posting: {} to slack".format(message))
response = requests.post(slack_webhook, json={"text": message})
logging.getLogger().info("Status code: {}".format(response.status_code))
def initialize_logging(log_file):
"""
Setup logging
:param log_file: (string) The file to log to
:return: (Logger) a logging instance
"""
# initialize logging
formatter = logging.Formatter("[%(asctime)s] [%(filename)30s:%(lineno)4s - %(funcName)30s()]\
[%(threadName)5s] [%(name)10.10s] [%(levelname)8s] %(message)s")
# Grab the root logger
logger = logging.getLogger()
# Set the root logger logging level (DEBUG, INFO, WARNING, ERROR, CRITICAL)
logger.setLevel(logging.DEBUG)
# Create a handler to print to the console
sh = logging.StreamHandler(sys.stdout)
sh.setFormatter(formatter)
sh.setLevel(logging.INFO)
# Create a handler to log to the specified file
rh = logging.handlers.RotatingFileHandler(log_file, mode='a', maxBytes=10485760)
rh.setFormatter(formatter)
rh.setLevel(logging.DEBUG)
# Add the handlers to the root logger
logger.addHandler(sh)
logger.addHandler(rh)
return logger
def initialize_db(db):
"""
Initializes the database and creates the table if necessary
:param db: (string) The database to use
:return:
"""
conn = sqlite3.connect(db)
c = conn.cursor()
c.execute("CREATE TABLE IF NOT EXISTS `Assignments` ( "
"`OBJECTID` INTEGER, "
"`description` TEXT, "
"`status` TEXT, "
"`notes` TEXT, "
"`priority` INTEGER, "
"`assignmentType` INTEGER, "
"`workerOrderId` TEXT, "
"`dueDate` INTEGER, "
"`workerId` INTEGER, "
"`GlobalID` TEXT UNIQUE, "
"`location` TEXT, "
"`declinedComment` TEXT, "
"`assignedDate` INTEGER, "
"`assignmentRead` INTEGER, "
"`inProgressDate` INTEGER, "
"`completedDate` INTEGER, "
"`declinedDate` INTEGER, "
"`pausedDate` INTEGER, "
"`dispatcherId` INTEGER, "
"`CreationDate` INTEGER, "
"`Creator` TEXT, "
"`EditDate` INTEGER, "
"`Editor` TEXT, "
"PRIMARY KEY(`GlobalID`) )")
conn.commit()
conn.close()
def add_assignment_to_db(db, assignment):
"""
Adds an assignment to the database
:param db: (string) The database to connect to
:param assignment: (Feature) The assignment to add
:return:
"""
conn = sqlite3.connect(db)
c = conn.cursor()
params = (
assignment.attributes["OBJECTID"],
assignment.attributes["description"],
assignment.attributes["status"],
assignment.attributes["notes"],
assignment.attributes["priority"],
assignment.attributes["assignmentType"],
assignment.attributes["workOrderId"],
assignment.attributes["dueDate"],
assignment.attributes["workerId"],
assignment.attributes["GlobalID"],
assignment.attributes["location"],
assignment.attributes["declinedComment"],
assignment.attributes["assignedDate"],
assignment.attributes["assignmentRead"],
assignment.attributes["inProgressDate"],
assignment.attributes["completedDate"],
assignment.attributes["declinedDate"],
assignment.attributes["pausedDate"],
assignment.attributes["dispatcherId"],
assignment.attributes["CreationDate"],
assignment.attributes["Creator"],
assignment.attributes["EditDate"],
assignment.attributes["Editor"]
)
c.execute("INSERT INTO assignments VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", params)
conn.commit()
conn.close()
def get_global_ids(db):
"""
Gets all global ids in the database
:param db: (string) The database to query
:return: List<string> The global ids in the db
"""
conn = sqlite3.connect(db)
c = conn.cursor()
c.execute("Select GlobalID from assignments")
global_ids = [r[0] for r in c.fetchall()]
return global_ids
if __name__ == "__main__":
# parse the config file
config = configparser.ConfigParser()
config.read("config.ini")
logger = initialize_logging(config["LOG"]["LOGFILE"])
initialize_db(config["DB"]["DATABASE"])
# Authenticate and get data
logger.info("Authenticating with ArcGIS Online...")
gis = arcgis.gis.GIS(config["AGOL"]["ORG"], username=config["AGOL"]["USERNAME"], password=config["AGOL"]["PASSWORD"])
logger.info("Getting project info...")
project_data = arcgis.gis.Item(gis, config["WORKFORCE"]["PROJECT"]).get_data()
assignment_feature_layer = arcgis.features.FeatureLayer(project_data["assignments"]["url"], gis)
# the list of global ids that have been sent to slack already
logger.info("Reading processed assignments from database...")
processed_global_ids = get_global_ids(config["DB"]["DATABASE"])
# Loop indefinitely
while True:
logger.info("Querying assignments...")
assignments = assignment_feature_layer.query(where="Status=3").features
logger.info("Processing assignments...")
for assignment in assignments:
if not assignment.attributes["GlobalID"] in processed_global_ids:
logger.info("Adding new assignment to sqlite database...")
processed_global_ids.append(assignment.attributes["GlobalID"])
# append the global id to the csv file (in-case we need to restart script)
add_assignment_to_db(config["DB"]["DATABASE"], assignment)
# post message to slack, if configured
if config.has_section("SLACK") and config.has_option("SLACK","WEBHOOK"):
logger.info("Posting assignment to slack...")
post_to_slack(config["SLACK"]["WEBHOOK"], assignment, config["WORKFORCE"]["PROJECT"])
# sleep for 5 seconds before polling again
logger.info("Sleeping for 5 seconds...")
time.sleep(5)