Passed
Push — master ( cb176a...4b8481 )
by
unknown
13:30
created

core.ticket.TicketItem.on_put()   B

Complexity

Conditions 5

Size

Total Lines 34
Code Lines 20

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 20
dl 0
loc 34
rs 8.9332
c 0
b 0
f 0
cc 5
nop 3
1
from datetime import datetime, timedelta, timezone
2
import falcon
3
from core.useractivity import user_logger, access_control
4
import simplejson as json
5
import time
6
import hashlib
7
import requests
8
import config
9
10
11
class TicketCollection:
12
    """
13
    Ticket Collection Resource
14
15
    This class handles ticket operations for the MyEMS workflow system.
16
    It provides functionality to retrieve tickets from the workflow service
17
    with filtering by date range and status.
18
    """
19
20
    def __init__(self):
21
        pass
22
23
    @staticmethod
24
    def on_options(req, resp):
25
        """
26
        Handle OPTIONS request for CORS preflight
27
28
        Args:
29
            req: Falcon request object
30
            resp: Falcon response object
31
        """
32
        _ = req
33
        resp.status = falcon.HTTP_200
34
35
    @staticmethod
36
    def on_get(req, resp):
37
        """
38
        Handle GET requests to retrieve tickets from workflow system
39
40
        Retrieves tickets based on date range and status filters.
41
        Communicates with the MyEMS workflow service to fetch ticket data.
42
43
        Args:
44
            req: Falcon request object with query parameters:
45
                - startdatetime: Start date for filtering (required)
46
                - enddatetime: End date for filtering (required)
47
                - status: Ticket status filter (required)
48
            resp: Falcon response object
49
        """
50
        access_control(req)
51
        start_datetime_local = req.params.get('startdatetime')
52
        end_datetime_local = req.params.get('enddatetime')
53
        status = req.params.get('status')
54
55
        # Calculate timezone offset for datetime conversion
56
        timezone_offset = int(config.utc_offset[1:3]) * 60 + int(config.utc_offset[4:6])
57
        if config.utc_offset[0] == '-':
58
            timezone_offset = -timezone_offset
59
60
        # Validate and parse start datetime
61
        if start_datetime_local is None:
62
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
63
                                   description="API.INVALID_START_DATETIME_FORMAT")
64
        else:
65
            start_datetime_local = str.strip(start_datetime_local)
66
            try:
67
                start_datetime_utc = datetime.strptime(start_datetime_local,
68
                                                       '%Y-%m-%dT%H:%M:%S').replace(tzinfo=timezone.utc) - \
69
                                     timedelta(minutes=timezone_offset)
70
            except ValueError:
71
                raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
72
                                       description="API.INVALID_START_DATETIME_FORMAT")
73
74
        # Validate and parse end datetime
75
        if end_datetime_local is None:
76
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
77
                                   description="API.INVALID_END_DATETIME_FORMAT")
78
        else:
79
            end_datetime_local = str.strip(end_datetime_local)
80
            try:
81
                end_datetime_utc = datetime.strptime(end_datetime_local,
82
                                                     '%Y-%m-%dT%H:%M:%S').replace(tzinfo=timezone.utc) - \
83
                                   timedelta(minutes=timezone_offset)
84
            except ValueError:
85
                raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
86
                                       description="API.INVALID_END_DATETIME_FORMAT")
87
88
        # Validate date range
89
        if start_datetime_utc >= end_datetime_utc:
90
            raise falcon.HTTPError(status=falcon.HTTP_400,
91
                                   title='API.BAD_REQUEST',
92
                                   description='API.START_DATETIME_MUST_BE_EARLIER_THAN_END_DATETIME')
93
94
        # Validate status parameter
95 View Code Duplication
        if status is None:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
96
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
97
                                   description="API.INVALID_STATUS")
98
        else:
99
            status = str.lower(str.strip(status))
100
            if status not in ['new', 'read', 'acknowledged', 'all']:
101
                raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
102
                                       description='API.INVALID_STATUS')
103
            else:
104
                if status == 'all':
105
                    status_query = ""
106
                else:
107
                    status_query = "status = '" + status + "' AND "
108
109
        # Prepare workflow service authentication
110
        workflow_base_url = config.myems_workflow['base_url']
111
        token = config.myems_workflow['token']
112
        app_name = config.myems_workflow['app_name']
113
        user_name = config.myems_workflow['user_name']
114
115
        # Generate authentication signature
116
        timestamp = str(time.time())[:10]
117
        ori_str = timestamp + token
118
        signature = hashlib.md5(ori_str.encode(encoding='utf-8')).hexdigest()
119
        headers = dict(signature=signature, timestamp=timestamp, appname=app_name, username=user_name)
120
121
        # Request tickets from workflow service
122
        get_data = dict(per_page=20, category='all')
123
        r = requests.get(workflow_base_url + 'tickets', headers=headers, params=get_data)
124
        resp.text = json.dumps(r.text)
125
126
127
class TicketItem:
128
    """
129
    Ticket Item Resource
130
131
    This class handles individual ticket operations including:
132
    - Retrieving a specific ticket by ID
133
    - Updating ticket status
134
    - Deleting tickets
135
    """
136
137
    def __init__(self):
138
        pass
139
140
    @staticmethod
141
    def on_options(req, resp, id_):
142
        """
143
        Handle OPTIONS request for CORS preflight
144
145
        Args:
146
            req: Falcon request object
147
            resp: Falcon response object
148
            id_: Ticket ID parameter
149
        """
150
        _ = req
151
        resp.status = falcon.HTTP_200
152
        _ = id_
153
154
    @staticmethod
155
    def on_get(req, resp, id_):
156
        """
157
        Handle GET requests to retrieve a specific ticket by ID
158
159
        Retrieves a single ticket from the workflow service based on the provided ID.
160
161
        Args:
162
            req: Falcon request object
163
            resp: Falcon response object
164
            id_: Ticket ID to retrieve
165
        """
166
        access_control(req)
167
        if not id_.isdigit() or int(id_) <= 0:
168
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
169
                                   description='API.INVALID_TICKET_ID')
170
171
        # Prepare workflow service authentication
172
        workflow_base_url = config.myems_workflow['base_url']
173
        token = config.myems_workflow['token']
174
        app_name = config.myems_workflow['app_name']
175
        user_name = config.myems_workflow['user_name']
176
177
        # Generate authentication signature
178
        timestamp = str(time.time())[:10]
179
        ori_str = timestamp + token
180
        signature = hashlib.md5(ori_str.encode(encoding='utf-8')).hexdigest()
181
        headers = dict(signature=signature, timestamp=timestamp, appname=app_name, username=user_name)
182
183
        # Request specific ticket from workflow service
184
        get_data = dict()
185
        r = requests.get(workflow_base_url + 'tickets/' + str(id_), headers=headers, params=get_data)
186
        resp.text = json.dumps(r.text)
187
188
    @staticmethod
189
    @user_logger
190
    def on_put(req, resp, id_):
191
        """
192
        Handle PUT requests to update a ticket
193
194
        Updates a specific ticket in the workflow system.
195
        Currently marked as TODO - implementation pending.
196
197
        Args:
198
            req: Falcon request object containing update data
199
            resp: Falcon response object
200
            id_: Ticket ID to update
201
        """
202
        access_control(req)
203
        try:
204
            raw_json = req.stream.read().decode('utf-8')
205
        except UnicodeDecodeError as ex:
206
            print("Failed to decode request")
207
            raise falcon.HTTPError(status=falcon.HTTP_400,
208
                                   title='API.BAD_REQUEST',
209
                                   description='API.INVALID_ENCODING')
210
        except Exception as ex:
211
            print("Unexpected error reading request stream")
212
            raise falcon.HTTPError(status=falcon.HTTP_400,
213
                                   title='API.BAD_REQUEST',
214
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
215
216
        if not id_.isdigit() or int(id_) <= 0:
217
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
218
                                   description='API.INVALID_TICKET_ID')
219
220
        # TODO: Implement ticket update functionality
221
        resp.status = falcon.HTTP_200
222
223
    @staticmethod
224
    @user_logger
225
    def on_delete(req, resp, id_):
226
        """
227
        Handle DELETE requests to remove a ticket
228
229
        Deletes a specific ticket from the workflow system.
230
        Currently marked as TODO - implementation pending.
231
232
        Args:
233
            req: Falcon request object
234
            resp: Falcon response object
235
            id_: Ticket ID to delete
236
        """
237
        access_control(req)
238
        if not id_.isdigit() or int(id_) <= 0:
239
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
240
                                   description='API.INVALID_TICKET_ID')
241
        # TODO: Implement ticket deletion functionality
242
        resp.status = falcon.HTTP_204
243
244