-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcasestory.py
184 lines (161 loc) · 5.17 KB
/
casestory.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
# Copyright 2021 DataStax, Inc
import asyncio
from io import StringIO
import os
import logging
from datetime import timezone
import requests
from aiosfstream import Client, RefreshTokenAuthenticator, PasswordAuthenticator
from simple_salesforce import Salesforce, SalesforceExpiredSession
# visualization
import plotly.express as px
import pandas as pd
username = ""
password = ""
token = ""
client_id = ""
client_secret = ""
refresh_token = ""
sandbox = False # change if using the production version of salesforce
agent_dict = {}
with open("agents.txt") as f:
lines = f.readlines()
for line in lines:
result = [x.strip() for x in line.split(",")]
agent_dict[result[1]] = result[0]
class Extract:
def __init__(self):
self.sf_auth()
def sf_auth(self):
domain = "test" if sandbox else "login"
if refresh_token is not None:
params = {
"grant_type": "refresh_token",
"redirect_uri": f"https://{domain}.salesforce.com/",
"client_id": client_id,
"client_secret": client_secret,
"refresh_token": refresh_token,
}
url = f"https://{domain}.salesforce.com/services/oauth2/token"
response = requests.post(url, params=params).json()
print(response)
self.sf = Salesforce(
instance_url=response["instance_url"],
session_id=response["access_token"],
)
else:
self.sf = Salesforce(
username=username,
password=password,
security_token=token,
domain=domain,
)
def query(self, stmt, retry=True):
try:
return self.sf.query_all_iter(stmt)
except SalesforceExpiredSession as ex:
if not retry:
raise ex
self.sf_auth()
return self.query(stmt, retry=False)
casenumber = input("Case Number: ")
try:
val = int(casenumber)
except ValueError:
raise RuntimeError("Please put in a valid CaseNumber")
caseid_stmt = f"""
SELECT Id, CaseNumber FROM Case WHERE CaseNumber = '{casenumber}'
"""
sf = Extract()
sf.sf_auth()
caseidresult = sf.query(caseid_stmt)
caseid = " "
for result in caseidresult:
caseid = result["Id"]
query_stmt = f"""
SELECT Id, CreatedDate, Comment__c, Case__c, Public__c, CommentAuthor__c FROM Conversation__c WHERE Case__c = '{caseid}'
"""
raw_data = sf.query(query_stmt)
datastax_external = []
datastax_internal = []
customer = []
lastResponse = []
timestamp = []
date = []
date_bucket = []
total = []
external = []
internal = []
customerC = []
for comments in raw_data:
count = 0
counte = 0
counti = 0
countc = 0
if comments["Public__c"] == False:
datastax_internal.append(comments)
timestamp.append(pd.to_datetime(comments["CreatedDate"]))
date.append(pd.to_datetime(comments["CreatedDate"]).date())
lastResponse.append('Support')
count = count + 1
total.append(count)
counti = counti + 1
internal.append(counti)
counte = counte
external.append(counte)
countc = countc
customerC.append(countc)
if (
str(comments["CommentAuthor__c"]) not in agent_dict
and comments["Public__c"] == True
):
# print(comments["Comment__c"])
timestamp.append(pd.to_datetime(comments["CreatedDate"]))
date.append(pd.to_datetime(comments["CreatedDate"]).date())
lastResponse.append('Customer')
customer.append(comments)
count = count + 1
total.append(count)
countc = countc + 1
customerC.append(countc)
counte = counte
external.append(counte)
counti = counti
internal.append(counti)
else:
timestamp.append(pd.to_datetime(comments["CreatedDate"]))
date.append(pd.to_datetime(comments["CreatedDate"]).date())
lastResponse.append('Support')
datastax_external.append(comments)
count = count + 1
total.append(count)
counte = counte + 1
external.append(counte)
counti = counti
internal.append(counti)
countc = countc
customerC.append(countc)
print(datastax_external)
print(datastax_internal)
print(customer)
print(lastResponse)
print(date)
print(total)
print(external)
print(internal)
print(customerC)
#Visualization
d = {'date': date, 'timestamp': timestamp, 'external': external, 'internal': internal, 'customer': customerC, 'total': total , 'lastResponse': lastResponse}
df = pd.DataFrame(data=d)
print(df)
fig = px.bar(df, x='timestamp', y='total', title='Ticket story', color='lastResponse')
fig2 = px.bar(df, x='date', y='total', title='Ticket story', color='lastResponse')
import dash
import dash_core_components as dcc
import dash_html_components as html
app = dash.Dash()
app.layout = html.Div([
dcc.Graph(figure=fig),
dcc.Graph(figure=fig2)
])
app.run_server(debug=True, use_reloader=False)