-
Notifications
You must be signed in to change notification settings - Fork 243
Expand file tree
/
Copy pathbase.py
More file actions
313 lines (248 loc) · 9.69 KB
/
base.py
File metadata and controls
313 lines (248 loc) · 9.69 KB
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
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
from urllib.parse import urljoin
import requests
import frappe
from frappe import _
from frappe.utils import sbool
from frappe.utils.scheduler import is_scheduler_disabled
from india_compliance.exceptions import GatewayTimeoutError, GSPServerError
from india_compliance.gst_india.utils import is_api_enabled
from india_compliance.gst_india.utils.api import enqueue_integration_request
BASE_URL = "https://asp.resilient.tech"
class BaseAPI:
API_NAME = "GST"
BASE_PATH = ""
SENSITIVE_INFO = ("x-api-key",)
def __init__(self, *args, **kwargs):
self.settings = frappe.get_cached_doc("GST Settings")
if not is_api_enabled(self.settings):
frappe.throw(
_("Please enable API in GST Settings to use the {0} API").format(
self.API_NAME
)
)
self.sandbox_mode = self.settings.sandbox_mode
self.default_headers = {
"x-api-key": (
(self.settings.api_secret and self.settings.get_password("api_secret"))
or frappe.conf.ic_api_secret
)
}
self.default_log_values = {}
self.setup(*args, **kwargs)
def setup(*args, **kwargs):
# Override in subclass
pass
def fetch_credentials(self, gstin, service, require_password=True):
for row in self.settings.credentials:
if row.gstin == gstin and row.service == service:
break
else:
frappe.throw(
_(
"Please set the relevant credentials for GSTIN {0} in GST Settings to use the"
" {1} API"
).format(gstin, self.API_NAME),
frappe.DoesNotExistError,
title=_("Credentials Unavailable"),
)
self.username = row.username
self.company = row.company
self._fetch_credentials(row, require_password=require_password)
def _fetch_credentials(self, row, require_password=True):
self.password = row.get_password(raise_exception=require_password)
def get_url(self, *parts):
parts = list(parts)
# If the first part is a URL, return it as it is
if parts and parts[0].startswith("https"):
return parts[0]
if self.BASE_PATH:
parts.insert(0, self.BASE_PATH)
if self.sandbox_mode:
parts.insert(0, "test")
return urljoin(BASE_URL, "/".join(part.strip("/") for part in parts))
def get(self, *args, **kwargs):
return self._make_request("GET", *args, **kwargs)
def post(self, *args, **kwargs):
return self._make_request("POST", *args, **kwargs)
def _make_request(
self,
method,
endpoint="",
params=None,
headers=None,
json=None,
):
method = method.upper()
if method not in ("GET", "POST"):
frappe.throw(_("Invalid method {0}").format(method))
request_args = frappe._dict(
url=self.get_url(endpoint),
params=params,
headers={
# auto-generated hash, required by some endpoints
**self.default_headers,
**(headers or {}),
},
)
log_headers = request_args.headers.copy()
log = frappe._dict(
**self.default_log_values,
url=request_args.url,
data=request_args.params,
request_headers=log_headers,
)
if method == "POST" and json:
request_args.json = json
json_data = json.copy()
if not request_args.params:
log.data = json_data
else:
log.data = {
"params": request_args.params,
"body": json_data,
}
response = None
response_json = None
try:
self.before_request(request_args)
response = requests.request(method, **request_args)
if api_request_id := response.headers.get("x-amzn-RequestId"):
log.request_id = api_request_id
try:
response_json = response.json(object_hook=frappe._dict)
except Exception:
pass
# Raise special error for certain HTTP codes
self.handle_http_code(response.status_code, response_json)
# Raise HTTPError for other HTTP codes
response.raise_for_status()
# Expect all successful responses to be JSON
if not response_json:
if "tar.gz" in request_args.url:
response_json = response.content
else:
frappe.throw(
_("Error parsing response: {0}").format(response.content)
)
response_json = self.process_response(response_json)
if response_json.get("error_type") == "invalid_public_key":
return self._make_request(method, endpoint, params, headers, json)
return response_json.get("result", response_json)
except Exception as e:
log.error = str(e)
raise e
finally:
if response_json:
log.output = response_json.copy()
elif response:
log.output = {
"status_code": response.status_code,
"content": response.text,
}
self.mask_sensitive_info(log)
enqueue_integration_request(**log)
if self.sandbox_mode and not frappe.flags.ic_sandbox_message_shown:
frappe.msgprint(
_("GST API request was made in Sandbox Mode"),
alert=True,
)
frappe.flags.ic_sandbox_message_shown = True
def before_request(self, request_args):
return
def process_response(self, response):
self.handle_error_response(response)
self.response = response
return response
def handle_error_response(self, response_json):
# All error responses have a success key set to false
success_value = response_json.get("success", True)
if isinstance(success_value, str):
success_value = sbool(success_value)
if not success_value:
self.handle_server_error(response_json)
if not success_value and not self.is_ignored_error(response_json):
frappe.throw(
response_json.get("message")
# Fallback to response body if message is not present
or frappe.as_json(response_json, indent=4),
title=_("API Request Failed"),
)
def handle_server_error(self, response_json):
error_message_list = [
"GSPGSTDOWN",
"GSPERR300",
"Connection reset",
"No route to host",
]
for error in error_message_list:
if error in response_json.get("message"):
raise GSPServerError
def is_ignored_error(self, response_json):
# Override in subclass, return truthy value to stop frappe.throw
pass
def handle_http_code(self, status_code, response_json):
# GSP connectivity issues
if status_code == 401 or (
status_code == 403
and response_json
and response_json.get("error") == "access_denied"
):
frappe.throw(
_(
"Error establishing connection to GSP. Please contact India"
" Compliance API support at <strong>api-support@indiacompliance.app</strong>."
),
title=_("GSP Connection Error"),
)
# ASP connectivity issues
if status_code == 429:
frappe.throw(
_("Your India Compliance API credits have exhausted"),
title=_("API Credits Exhausted"),
)
if status_code == 403:
frappe.throw(
_("Your India Compliance API key is invalid"),
title=_("Invalid API Key"),
)
if status_code == 504:
raise GatewayTimeoutError
def generate_request_id(self, length=12):
return frappe.generate_hash(length=length)
def mask_sensitive_info(self, log):
request_headers = log.request_headers
output = log.output
data = log.data
request_body = data and data.get("body")
placeholder = "*****"
for key in self.SENSITIVE_INFO:
if key in request_headers:
request_headers[key] = placeholder
if output and key in output:
output[key] = placeholder
if not data:
continue
if key in data:
data[key] = placeholder
if request_body and key in request_body:
request_body[key] = placeholder
def check_scheduler_status():
"""
Throw an error if scheduler is disabled
"""
if frappe.flags.in_test or frappe.conf.developer_mode:
return
if is_scheduler_disabled():
frappe.throw(
_(
"The Scheduler is currently disabled, which needs to be enabled to use e-Invoicing and e-Waybill features. "
"Please get in touch with your server administrator to resolve this issue.<br><br>"
"For more information, refer to the following documentation: {0}"
).format(
"""
<a href="https://frappeframework.com/docs/user/en/bench/resources/bench-commands-cheatsheet#scheduler" target="_blank">
Frappe Scheduler Documentation
</a>
"""
)
)