· 6 years ago · Oct 11, 2019, 11:42 AM
1import lime_webserver.webserver as webserver
2import logging
3import pytz
4from ..endpoints import api
5from datetime import datetime, timedelta
6from lime_query import execute_query
7
8logger = logging.getLogger(__name__)
9
10# This describes the schema for the payload when posting a new deal
11# See https://webargs.readthedocs.io/en/latest/ for more info.
12
13
14class Scheduling(webserver.LimeResource):
15 """ Endpoint responsible for creating scheduled helpdesks
16 """
17
18 def get(self):
19 app = self.application
20
21 # schedule runs only monday to friday
22 today = datetime.today()
23 weekdays = range(0, 5)
24 helpdesks = []
25
26 import pdb; pdb.set_trace()
27
28 if today.weekday() in weekdays:
29 # create unit of work
30 uow = app.unit_of_work()
31
32 # get available scheduling intervals
33 intervals = app.limetypes.scheduling.get_property('interval')
34
35 # run scheduling for all available intervals
36 for option in intervals.options:
37 if option.text != '':
38 new_helpdesks = run(app=app, uow=uow, interval=option.key,
39 date=today)
40 helpdesks.append(new_helpdesks)
41
42 uow.commit()
43
44 return str(helpdesks)
45
46
47def run(app, uow, interval, date):
48 schedules = get_schedules(app=app, interval=interval, date=date)
49 schedule_objects = schedules['objects']
50
51 helpdesks = []
52 for o in schedule_objects:
53 # get original deal to copy from
54 original_helpdesk = get_helpdesk(app=app, helpdeskno=o['scheduleid'])
55
56 if original_helpdesk:
57 # check if copy exists
58 exists = copy_exists(app=app, scheduleid=o['scheduleid'],
59 interval=interval, today=date)
60
61 if not exists:
62 # copy original deal
63 new_helpdesk = copy(app=app, uow=uow,
64 limeobject=original_helpdesk)
65 # give copy scheduleid
66 new_helpdesk.properties.scheduleid.value = o['scheduleid']
67 # append and add
68 helpdesks.append(new_helpdesk)
69 uow.add(new_helpdesk)
70
71 return helpdesks
72
73
74def copy(app, uow, limeobject):
75 limetype = app.limetypes.get_limetype(limeobject.limetype.name)
76 new_object = limetype()
77
78 # copy properties
79 properties = limeobject.get_non_relational_properties()
80 for p in properties:
81 new_object.get_property(p.name).value = limeobject.get_property(p.name).value
82
83 # copy relations
84 relations = limeobject.get_relations()
85 existing_relations = [x for x in relations if x.value is not None]
86 for r in existing_relations:
87 related_object = limeobject.get_property(r.name).fetch()
88 if related_object:
89 new_object.get_property(r.name).attach(related_object)
90 uow.add(related_object)
91
92 return new_object
93
94
95def get_intervaldates(interval, today):
96 if interval == 'day':
97 begin = datetime(today.year, today.month, today.day)
98 end = begin + timedelta(days=+1)
99 elif interval == 'week':
100 target = datetime(today.year, today.month, today.day)
101 begin = target - timedelta(days=today.weekday())
102 end = target + timedelta(days=6)
103 elif interval == 'month':
104 nextmonth = today.month % 12 + 1
105 begin = datetime(today.year, today.month, 1)
106 end = datetime(today.year, nextmonth, 1)
107 elif interval == 'year':
108 nextyear = today.year + 1
109 begin = datetime(today.year, 1, 1)
110 end = datetime(nextyear, 1, 1)
111 else:
112 raise IntervalError('Invalid interval.')
113
114 # give dates timezone
115 utc = pytz.utc
116 begin = utc.localize(begin)
117 end = utc.localize(end)
118
119 return begin, end
120
121
122def copy_exists(app, interval, scheduleid, today):
123 # get interval dates first
124 try:
125 begin, end = get_intervaldates(interval=interval, today=today)
126 except IntervalError:
127 pass
128
129 query = {
130 'limetype': 'helpdesk',
131 'limit': 200,
132 'responseFormat': {
133 'object': {
134 '_id': None,
135 '_createdtime': None,
136 'title': None,
137 'helpdeskno': None,
138 'scheduleid': None
139 }
140 },
141 'filter': {
142 'op': 'AND',
143 'exp': [
144 {'op': '=', 'key': 'scheduleid', 'exp': scheduleid},
145 {'op': '<', 'key': '_createdtime', 'exp': end},
146 {'op': '>=', 'key': '_createdtime', 'exp': begin}
147 ]
148 }
149 }
150 response = execute_query(
151 query=query,
152 conn=app.database.connection,
153 limetypes=app.limetypes,
154 acl=app.acl,
155 user=app.user
156 )
157
158 exists = True
159 if len(response['objects']) == 0:
160 exists = False
161 else:
162 exists = True
163
164 return exists
165
166
167def get_helpdesk(app, helpdeskno):
168 query = {
169 'limetype': 'helpdesk',
170 'limit': 1,
171 'responseFormat': {
172 'object': {
173 '_id': None,
174 'title': None,
175 'helpdeskno': None
176 }
177 },
178 'filter': {
179 'op': 'AND',
180 'exp': [
181 {'op': '=', 'key': 'helpdeskno', 'exp': helpdeskno}
182 ]
183 }
184 }
185 response = execute_query(
186 query=query,
187 conn=app.database.connection,
188 limetypes=app.limetypes,
189 acl=app.acl,
190 user=app.user
191 )
192
193 try:
194 helpdesk = app.limetypes.helpdesk.get(response['objects'][0]['_id'])
195 return helpdesk
196
197 except IndexError:
198 print('There is no helpdesk with helpdesknumber ' + str(helpdeskno))
199
200
201def get_schedules(app, interval, date):
202 query = {
203 'limetype': 'scheduling',
204 'responseFormat': {
205 'object': {
206 '_id': None,
207 'scheduleid': None,
208 'start': None,
209 'end': None
210 }
211 },
212 'filter': {
213 'op': 'AND',
214 'exp': [
215 {'op': '=', 'key': 'interval', 'exp': interval},
216 {'op': '<', 'key': 'start', 'exp': date},
217 {'op': '>=', 'key': 'end', 'exp': date + timedelta(days=-1)}
218 ]
219 }
220 }
221 response = execute_query(
222 query=query,
223 conn=app.database.connection,
224 limetypes=app.limetypes,
225 acl=app.acl,
226 user=app.user
227 )
228
229 return response
230
231
232api.add_resource(Scheduling, '/scheduling/')