Repository: fossasia/open-event-server

Issue:
HTTP 422 in creating Access-codes
**Describe the bug**
<!-- A clear and concise description of what the bug is. -->
The Server sends HTTP 422 Unprocessable entity when making a POST request like this:
``` Javascript
"attributes": {
      "code": "AC105",
      "access-url": "https://my-access-code-url.com",
      "is-active": "true",
      "tickets-number": "105",
      "min-quantity": null,
      "max-quantity": null,
      "valid-from": "2018-05-18T18:30:00+00:00",
      "valid-till": "2018-08-24T18:30:00+00:00"
    }
```
The problem is in the fact that min-quantity and the max-quantity are null which it can be when making requests from Java or JS. These are optional fields and hence these kind of errors shouldn't occur.

**To Reproduce**
Steps to reproduce the behavior:
1. Make a request like this.

**Expected behavior**
<!-- A clear and concise description of what you expected to happen. -->

**Stacktrace**
<!-- If applicable, add stacktrace to help explain your problem. -->
```Python
127.0.0.1 - - [28/May/2018 19:25:10] "POST /v1/access-codes HTTP/1.1" 500 -
INFO:werkzeug:127.0.0.1 - - [28/May/2018 19:25:10] "POST /v1/access-codes HTTP/1.1" 500 -
Traceback (most recent call last):
  File "/home/srv_twry/anaconda3/envs/open-event-server/lib/python3.6/site-packages/flask/app.py", line 2309, in __call__
    return self.wsgi_app(environ, start_response)
  File "/media/srv_twry/work/Projects/Community-Projects/Fossasia/open-event-server/app/__init__.py", line 64, in __call__
    return self.app(environ, start_response)
  File "/home/srv_twry/anaconda3/envs/open-event-server/lib/python3.6/site-packages/flask/app.py", line 2295, in wsgi_app
    response = self.handle_exception(e)
  File "/home/srv_twry/anaconda3/envs/open-event-server/lib/python3.6/site-packages/flask_cors/extension.py", line 161, in wrapped_function
    return cors_after_request(app.make_response(f(*args, **kwargs)))
  File "/home/srv_twry/anaconda3/envs/open-event-server/lib/python3.6/site-packages/flask/app.py", line 1741, in handle_exception
    reraise(exc_type, exc_value, tb)
  File "/home/srv_twry/anaconda3/envs/open-event-server/lib/python3.6/site-packages/flask/_compat.py", line 35, in reraise
    raise value
  File "/home/srv_twry/anaconda3/envs/open-event-server/lib/python3.6/site-packages/flask/app.py", line 2292, in wsgi_app
    response = self.full_dispatch_request()
  File "/home/srv_twry/anaconda3/envs/open-event-server/lib/python3.6/site-packages/flask/app.py", line 1815, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "/home/srv_twry/anaconda3/envs/open-event-server/lib/python3.6/site-packages/flask_cors/extension.py", line 161, in wrapped_function
    return cors_after_request(app.make_response(f(*args, **kwargs)))
  File "/home/srv_twry/anaconda3/envs/open-event-server/lib/python3.6/site-packages/flask/app.py", line 1718, in handle_user_exception
    reraise(exc_type, exc_value, tb)
  File "/home/srv_twry/anaconda3/envs/open-event-server/lib/python3.6/site-packages/flask/_compat.py", line 35, in reraise
    raise value
  File "/home/srv_twry/anaconda3/envs/open-event-server/lib/python3.6/site-packages/flask/app.py", line 1813, in full_dispatch_request
    rv = self.dispatch_request()
  File "/home/srv_twry/anaconda3/envs/open-event-server/lib/python3.6/site-packages/flask/app.py", line 1799, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "/media/srv_twry/work/Projects/Community-Projects/Fossasia/open-event-server/src/flask-rest-jsonapi/flask_rest_jsonapi/decorators.py", line 32, in wrapper
    return func(*args, **kwargs)
  File "/home/srv_twry/anaconda3/envs/open-event-server/lib/python3.6/site-packages/flask/views.py", line 88, in view
    return self.dispatch_request(*args, **kwargs)
  File "/media/srv_twry/work/Projects/Community-Projects/Fossasia/open-event-server/src/flask-rest-jsonapi/flask_rest_jsonapi/resource.py", line 68, in dispatch_request
    response = method(*args, **kwargs)
  File "/media/srv_twry/work/Projects/Community-Projects/Fossasia/open-event-server/src/flask-rest-jsonapi/flask_rest_jsonapi/decorators.py", line 56, in wrapper
    return func(*args, **kwargs)
  File "/media/srv_twry/work/Projects/Community-Projects/Fossasia/open-event-server/src/flask-rest-jsonapi/flask_rest_jsonapi/resource.py", line 182, in post
    data, errors = schema.load(json_data)
  File "/home/srv_twry/anaconda3/envs/open-event-server/lib/python3.6/site-packages/marshmallow/schema.py", line 578, in load
    result, errors = self._do_load(data, many, partial=partial, postprocess=True)
  File "/home/srv_twry/anaconda3/envs/open-event-server/lib/python3.6/site-packages/marshmallow_jsonapi/schema.py", line 232, in _do_load
    result = super(Schema, self)._do_load(data, many, **kwargs)
  File "/home/srv_twry/anaconda3/envs/open-event-server/lib/python3.6/site-packages/marshmallow/schema.py", line 673, in _do_load
    field_errors=field_errors)
  File "/home/srv_twry/anaconda3/envs/open-event-server/lib/python3.6/site-packages/marshmallow/schema.py", line 925, in _invoke_validators
    pass_original=pass_original)
  File "/home/srv_twry/anaconda3/envs/open-event-server/lib/python3.6/site-packages/marshmallow/marshalling.py", line 181, in run_validator
    res = validator_func(output, original_data)
  File "/media/srv_twry/work/Projects/Community-Projects/Fossasia/open-event-server/app/api/schema/access_codes.py", line 56, in validate_order_quantity
    if data['min_quantity'] >= data['max_quantity']:
TypeError: '>=' not supported between instances of 'NoneType' and 'NoneType'

```

**Found while working on** https://github.com/fossasia/open-event-frontend/pull/1104


Discussion:
Can we add a wrapping `if` statement?
```
if data['min_quantity'] is not None and data['max_quantity'] is not None:
    if data['min_quantity'] >= data['max_quantity']:
        ...
   ...
...
```
Yes, it should do the job. You can claim it if you want but it is blocking a PR on frontend so fix it now if you want to.
@srv-twry Okay, will do soon.

Resolving patch:
diff --git a/app/api/schema/access_codes.py b/app/api/schema/access_codes.py
--- a/app/api/schema/access_codes.py
+++ b/app/api/schema/access_codes.py
@@ -52,10 +52,14 @@ def validate_order_quantity(self, data, original_data):
             if 'tickets_number' not in data:
                 data['tickets_number'] = access_code.tickets_number
 
-        if 'min_quantity' in data and 'max_quantity' in data:
-            if data['min_quantity'] >= data['max_quantity']:
-                raise UnprocessableEntity({'pointer': '/data/attributes/min-quantity'},
-                                          "min-quantity should be less than max-quantity")
+        min_quantity = data.get('min_quantity', None)
+        max_quantity = data.get('max_quantity', None)
+        if min_quantity is not None and max_quantity is not None:
+            if min_quantity >= max_quantity:
+                raise UnprocessableEntity(
+                    {'pointer': '/data/attributes/min-quantity'},
+                    "min-quantity should be less than max-quantity"
+                )
 
         if 'tickets_number' in data and 'max_quantity' in data:
             if data['tickets_number'] < data['max_quantity']:
diff --git a/app/api/schema/discount_codes.py b/app/api/schema/discount_codes.py
--- a/app/api/schema/discount_codes.py
+++ b/app/api/schema/discount_codes.py
@@ -41,6 +41,17 @@ class Meta:
                          schema='EventSchemaPublic',
                          type_='event')
 
+    @classmethod
+    def quantity_validation_helper(obj, data):
+        min_quantity = data.get('min_quantity', None)
+        max_quantity = data.get('max_quantity', None)
+        if min_quantity is not None and max_quantity is not None:
+            if min_quantity >= max_quantity:
+                raise UnprocessableEntity(
+                    {'pointer': '/data/attributes/min-quantity'},
+                    "min-quantity should be less than max-quantity"
+                )
+
 
 class DiscountCodeSchemaEvent(DiscountCodeSchemaPublic):
     """
@@ -66,10 +77,7 @@ def validate_quantity(self, data, original_data):
             if 'tickets_number' not in data:
                 data['tickets_number'] = discount_code.tickets_number
 
-        if 'min_quantity' in data and 'max_quantity' in data:
-            if data['min_quantity'] >= data['max_quantity']:
-                raise UnprocessableEntity({'pointer': '/data/attributes/min-quantity'},
-                                          "min-quantity should be less than max-quantity")
+        DiscountCodeSchemaEvent.quantity_validation_helper(data)
 
         if 'tickets_number' in data and 'max_quantity' in data:
             if data['tickets_number'] < data['max_quantity']:
@@ -125,10 +133,7 @@ def validate_quantity(self, data, original_data):
             if 'tickets_number' not in data:
                 data['tickets_number'] = discount_code.tickets_number
 
-        if 'min_quantity' in data and 'max_quantity' in data:
-            if data['min_quantity'] >= data['max_quantity']:
-                raise UnprocessableEntity({'pointer': '/data/attributes/min-quantity'},
-                                          "min-quantity should be less than max-quantity")
+        DiscountCodeSchemaTicket.quantity_validation_helper(data)
 
         if 'tickets_number' in data and 'max_quantity' in data:
             if data['tickets_number'] < data['max_quantity']:


Test patch: