We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Access code should only be linked to hidden tickets
**Describe the bug**
<!-- A clear and concise description of what the bug is. -->
Right now we are allowing access code to be linked to any ticket.

**To Reproduce**
Steps to reproduce the behavior:
1. Create an access code linking it to a public ticket

**Expected behavior**
<!-- A clear and concise description of what you expected to happen. -->
We should only allow creating access codes for hidden tickets.

--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `app/api/schema/access_codes.py`
Content:
```
1 from marshmallow import validates_schema
2 from marshmallow_jsonapi import fields
3 from marshmallow_jsonapi.flask import Relationship
4 
5 from app.api.helpers.exceptions import UnprocessableEntity
6 from app.api.helpers.utilities import dasherize
7 from app.api.schema.base import SoftDeletionSchema
8 from app.models.access_code import AccessCode
9 from utils.common import use_defaults
10 
11 
12 @use_defaults()
13 class AccessCodeSchema(SoftDeletionSchema):
14     """
15     Api schema for Access Code Model
16     """
17 
18     class Meta:
19         """
20         Meta class for Access Code Api Schema
21         """
22         type_ = 'access-code'
23         self_view = 'v1.access_code_detail'
24         self_view_kwargs = {'id': '<id>'}
25         inflect = dasherize
26 
27     @validates_schema(pass_original=True)
28     def validate_date(self, data, original_data):
29         if 'id' in original_data['data']:
30             access_code = AccessCode.query.filter_by(id=original_data['data']['id']).one()
31 
32             if 'valid_from' not in data:
33                 data['valid_from'] = access_code.valid_from
34 
35             if 'valid_till' not in data:
36                 data['valid_till'] = access_code.valid_till
37 
38         if data['valid_from'] > data['valid_till']:
39             raise UnprocessableEntity({'pointer': '/data/attributes/valid-till'},
40                                       "valid_till should be after valid_from")
41 
42     @validates_schema(pass_original=True)
43     def validate_order_quantity(self, data, original_data):
44         if 'id' in original_data['data']:
45             access_code = AccessCode.query.filter_by(id=original_data['data']['id']).one()
46 
47             if 'min_quantity' not in data:
48                 data['min_quantity'] = access_code.min_quantity
49 
50             if 'max_quantity' not in data:
51                 data['max_quantity'] = access_code.max_quantity
52 
53             if 'tickets_number' not in data:
54                 data['tickets_number'] = access_code.tickets_number
55 
56         min_quantity = data.get('min_quantity', None)
57         max_quantity = data.get('max_quantity', None)
58         if min_quantity is not None and max_quantity is not None:
59             if min_quantity > max_quantity:
60                 raise UnprocessableEntity(
61                     {'pointer': '/data/attributes/min-quantity'},
62                     "min-quantity should be less than max-quantity"
63                 )
64 
65         if 'tickets_number' in data and 'max_quantity' in data:
66             if data['tickets_number'] < data['max_quantity']:
67                 raise UnprocessableEntity({'pointer': '/data/attributes/tickets-number'},
68                                           "tickets-number should be greater than max-quantity")
69 
70     id = fields.Integer(dump_ony=True)
71     code = fields.Str(required=True)
72     access_url = fields.Url(allow_none=True)
73     is_active = fields.Boolean(default=False)
74 
75     # For event level access this holds the max. uses
76     tickets_number = fields.Integer(validate=lambda n: n >= 0, allow_none=True)
77 
78     min_quantity = fields.Integer(validate=lambda n: n >= 0, allow_none=True)
79     max_quantity = fields.Integer(validate=lambda n: n >= 0, allow_none=True)
80     valid_from = fields.DateTime(required=True)
81     valid_till = fields.DateTime(required=True)
82     event = Relationship(attribute='event',
83                          self_view='v1.access_code_event',
84                          self_view_kwargs={'id': '<id>'},
85                          related_view='v1.event_detail',
86                          related_view_kwargs={'access_code_id': '<id>'},
87                          schema='EventSchemaPublic',
88                          type_='event')
89     marketer = Relationship(attribute='user',
90                             self_view='v1.access_code_user',
91                             self_view_kwargs={'id': '<id>'},
92                             related_view='v1.user_detail',
93                             related_view_kwargs={'access_code_id': '<id>'},
94                             schema='UserSchemaPublic',
95                             type_='user')
96     tickets = Relationship(attribute='tickets',
97                            self_view='v1.access_code_tickets',
98                            self_view_kwargs={'id': '<id>'},
99                            related_view='v1.ticket_list',
100                            related_view_kwargs={'access_code_id': '<id>'},
101                            schema='TicketSchemaPublic',
102                            many=True,
103                            type_='ticket')
104
```

Path: `app/api/access_codes.py`
Content:
```
1 from flask_rest_jsonapi import ResourceDetail, ResourceList, ResourceRelationship
2 from flask_rest_jsonapi.exceptions import ObjectNotFound
3 
4 from app.api.bootstrap import api
5 from app.api.helpers.db import safe_query
6 from app.api.helpers.exceptions import ForbiddenException, UnprocessableEntity
7 from app.api.helpers.permission_manager import has_access
8 from app.api.helpers.permissions import jwt_required
9 from app.api.helpers.query import event_query
10 from app.api.helpers.utilities import require_relationship
11 from app.api.schema.access_codes import AccessCodeSchema
12 from app.models import db
13 from app.models.access_code import AccessCode
14 from app.models.ticket import Ticket
15 from app.models.user import User
16 
17 
18 class AccessCodeListPost(ResourceList):
19     """
20     Create AccessCodes
21     """
22     def before_post(self, args, kwargs, data):
23         """
24         before post method to check for required relationships and permissions
25         :param args:
26         :param kwargs:
27         :param data:
28         :return:
29         """
30         require_relationship(['event', 'user'], data)
31         if not has_access('is_coorganizer', event_id=data['event']):
32             raise ForbiddenException({'source': ''}, "Minimum Organizer access required")
33 
34     schema = AccessCodeSchema
35     methods = ['POST', ]
36     data_layer = {'session': db.session,
37                   'model': AccessCode
38                   }
39 
40 
41 class AccessCodeList(ResourceList):
42     """
43     List AccessCodes
44     """
45     def query(self, view_kwargs):
46         """
47         Method to get access codes list based on different view_kwargs
48         :param view_kwargs:
49         :return:
50         """
51         query_ = self.session.query(AccessCode)
52         query_ = event_query(self, query_, view_kwargs, permission='is_coorganizer')
53         if view_kwargs.get('user_id'):
54             user = safe_query(self, User, 'id', view_kwargs['user_id'], 'user_id')
55             if not has_access('is_user_itself', user_id=user.id):
56                 raise ForbiddenException({'source': ''}, 'Access Forbidden')
57             query_ = query_.join(User).filter(User.id == user.id)
58         if view_kwargs.get('ticket_id'):
59             ticket = safe_query(self, Ticket, 'id', view_kwargs['ticket_id'], 'ticket_id')
60             if not has_access('is_coorganizer', event_id=ticket.event_id):
61                 raise ForbiddenException({'source': ''}, 'Access Forbidden')
62             # access_code - ticket :: many-to-many relationship
63             query_ = AccessCode.query.filter(AccessCode.tickets.any(id=ticket.id))
64             query_
65         return query_
66 
67     view_kwargs = True
68     methods = ['GET', ]
69     schema = AccessCodeSchema
70     data_layer = {'session': db.session,
71                   'model': AccessCode,
72                   'methods': {
73                       'query': query,
74                   }}
75 
76 
77 class AccessCodeDetail(ResourceDetail):
78     """
79     AccessCode detail by id or code
80     """
81     def before_get(self, args, kwargs):
82         """
83         before get method of access code details.
84         Check for permissions on the basis of kwargs.
85         :param args:
86         :param kwargs:
87         :return:
88         """
89         # Any registered user can fetch access code details using the code.
90         if kwargs.get('code'):
91             access = db.session.query(AccessCode).filter_by(code=kwargs.get('code')).first()
92             if access:
93                 kwargs['id'] = access.id
94             else:
95                 raise ObjectNotFound({'parameter': '{code}'}, "Access Code:  not found")
96             return
97 
98         # Co-organizer or the admin can fetch access code details using the id.
99         if kwargs.get('id'):
100             access = db.session.query(AccessCode).filter_by(id=kwargs.get('id')).one()
101             if not access:
102                 raise ObjectNotFound({'parameter': '{id}'}, "Access Code:  not found")
103 
104             if not has_access('is_coorganizer', event_id=access.event_id):
105                 raise UnprocessableEntity({'source': ''},
106                                           "Please verify your permission")
107 
108     decorators = (jwt_required, api.has_permission('is_coorganizer', fetch='event_id',
109                   fetch_as="event_id", model=AccessCode, methods="PATCH"),
110                   api.has_permission('is_coorganizer_but_not_admin', fetch='event_id',
111                   fetch_as="event_id", model=AccessCode, methods="DELETE"),)
112     schema = AccessCodeSchema
113     data_layer = {'session': db.session,
114                   'model': AccessCode
115                   }
116 
117 
118 class AccessCodeRelationshipRequired(ResourceRelationship):
119     """
120     AccessCode Relationship Required
121     """
122     decorators = (jwt_required,)
123     methods = ['GET', 'PATCH']
124     schema = AccessCodeSchema
125     data_layer = {'session': db.session,
126                   'model': AccessCode}
127 
128 
129 class AccessCodeRelationshipOptional(ResourceRelationship):
130     """
131     AccessCode Relationship Optional
132     """
133     decorators = (jwt_required,)
134     schema = AccessCodeSchema
135     data_layer = {'session': db.session,
136                   'model': AccessCode}
137
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/app/api/access_codes.py b/app/api/access_codes.py
--- a/app/api/access_codes.py
+++ b/app/api/access_codes.py
@@ -1,9 +1,11 @@
 from flask_rest_jsonapi import ResourceDetail, ResourceList, ResourceRelationship
 from flask_rest_jsonapi.exceptions import ObjectNotFound
+from sqlalchemy.orm.exc import NoResultFound
 
 from app.api.bootstrap import api
 from app.api.helpers.db import safe_query
-from app.api.helpers.exceptions import ForbiddenException, UnprocessableEntity
+from app.api.helpers.exceptions import ForbiddenException, ConflictException
+from app.api.helpers.exceptions import UnprocessableEntity
 from app.api.helpers.permission_manager import has_access
 from app.api.helpers.permissions import jwt_required
 from app.api.helpers.query import event_query
@@ -31,11 +33,33 @@
         if not has_access('is_coorganizer', event_id=data['event']):
             raise ForbiddenException({'source': ''}, "Minimum Organizer access required")
 
+    def before_create_object(self, data, view_kwargs):
+        """
+        before create object method for AccessCodeListPost Class
+        :param data:
+        :param view_kwargs:
+        :return:
+        """
+        if data.get('tickets', None):
+            for ticket in data['tickets']:
+                # Ensuring that the ticket exists and is hidden.
+                try:
+                    ticket_object = self.session.query(Ticket).filter_by(id=int(ticket),
+                                                                         deleted_at=None).one()
+                    if not ticket_object.is_hidden:
+                        raise ConflictException({'pointer': '/data/relationships/tickets'},
+                                                "Ticket with id {} is public.".format(ticket) +
+                                                " Access code cannot be applied to public tickets")
+                except NoResultFound:
+                    raise ConflictException({'pointer': '/data/relationships/tickets'},
+                                            "Ticket with id {} does not exists".format(str(ticket)))
+
     schema = AccessCodeSchema
     methods = ['POST', ]
     data_layer = {'session': db.session,
-                  'model': AccessCode
-                  }
+                  'model': AccessCode,
+                  'methods': {'before_create_object': before_create_object
+                              }}
 
 
 class AccessCodeList(ResourceList):
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
@@ -55,17 +55,16 @@
 
         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(
+        tickets_number = data.get('tickets_number', None)
+        if min_quantity and max_quantity and (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']:
-                raise UnprocessableEntity({'pointer': '/data/attributes/tickets-number'},
-                                          "tickets-number should be greater than max-quantity")
+        if tickets_number and max_quantity and (tickets_number < max_quantity):
+            raise UnprocessableEntity({'pointer': '/data/attributes/tickets-number'},
+                                      "tickets-number should be greater than max-quantity")
 
     id = fields.Integer(dump_ony=True)
     code = fields.Str(required=True)

{"golden_diff": "diff --git a/app/api/access_codes.py b/app/api/access_codes.py\n--- a/app/api/access_codes.py\n+++ b/app/api/access_codes.py\n@@ -1,9 +1,11 @@\n from flask_rest_jsonapi import ResourceDetail, ResourceList, ResourceRelationship\n from flask_rest_jsonapi.exceptions import ObjectNotFound\n+from sqlalchemy.orm.exc import NoResultFound\n \n from app.api.bootstrap import api\n from app.api.helpers.db import safe_query\n-from app.api.helpers.exceptions import ForbiddenException, UnprocessableEntity\n+from app.api.helpers.exceptions import ForbiddenException, ConflictException\n+from app.api.helpers.exceptions import UnprocessableEntity\n from app.api.helpers.permission_manager import has_access\n from app.api.helpers.permissions import jwt_required\n from app.api.helpers.query import event_query\n@@ -31,11 +33,33 @@\n         if not has_access('is_coorganizer', event_id=data['event']):\n             raise ForbiddenException({'source': ''}, \"Minimum Organizer access required\")\n \n+    def before_create_object(self, data, view_kwargs):\n+        \"\"\"\n+        before create object method for AccessCodeListPost Class\n+        :param data:\n+        :param view_kwargs:\n+        :return:\n+        \"\"\"\n+        if data.get('tickets', None):\n+            for ticket in data['tickets']:\n+                # Ensuring that the ticket exists and is hidden.\n+                try:\n+                    ticket_object = self.session.query(Ticket).filter_by(id=int(ticket),\n+                                                                         deleted_at=None).one()\n+                    if not ticket_object.is_hidden:\n+                        raise ConflictException({'pointer': '/data/relationships/tickets'},\n+                                                \"Ticket with id {} is public.\".format(ticket) +\n+                                                \" Access code cannot be applied to public tickets\")\n+                except NoResultFound:\n+                    raise ConflictException({'pointer': '/data/relationships/tickets'},\n+                                            \"Ticket with id {} does not exists\".format(str(ticket)))\n+\n     schema = AccessCodeSchema\n     methods = ['POST', ]\n     data_layer = {'session': db.session,\n-                  'model': AccessCode\n-                  }\n+                  'model': AccessCode,\n+                  'methods': {'before_create_object': before_create_object\n+                              }}\n \n \n class AccessCodeList(ResourceList):\ndiff --git a/app/api/schema/access_codes.py b/app/api/schema/access_codes.py\n--- a/app/api/schema/access_codes.py\n+++ b/app/api/schema/access_codes.py\n@@ -55,17 +55,16 @@\n \n         min_quantity = data.get('min_quantity', None)\n         max_quantity = data.get('max_quantity', None)\n-        if min_quantity is not None and max_quantity is not None:\n-            if min_quantity > max_quantity:\n-                raise UnprocessableEntity(\n+        tickets_number = data.get('tickets_number', None)\n+        if min_quantity and max_quantity and (min_quantity > max_quantity):\n+            raise UnprocessableEntity(\n                     {'pointer': '/data/attributes/min-quantity'},\n                     \"min-quantity should be less than max-quantity\"\n-                )\n+            )\n \n-        if 'tickets_number' in data and 'max_quantity' in data:\n-            if data['tickets_number'] < data['max_quantity']:\n-                raise UnprocessableEntity({'pointer': '/data/attributes/tickets-number'},\n-                                          \"tickets-number should be greater than max-quantity\")\n+        if tickets_number and max_quantity and (tickets_number < max_quantity):\n+            raise UnprocessableEntity({'pointer': '/data/attributes/tickets-number'},\n+                                      \"tickets-number should be greater than max-quantity\")\n \n     id = fields.Integer(dump_ony=True)\n     code = fields.Str(required=True)\n", "issue": "Access code should only be linked to hidden tickets\n**Describe the bug**\r\n<!-- A clear and concise description of what the bug is. -->\r\nRight now we are allowing access code to be linked to any ticket.\r\n\r\n**To Reproduce**\r\nSteps to reproduce the behavior:\r\n1. Create an access code linking it to a public ticket\r\n\r\n**Expected behavior**\r\n<!-- A clear and concise description of what you expected to happen. -->\r\nWe should only allow creating access codes for hidden tickets.\n", "before_files": [{"content": "from marshmallow import validates_schema\nfrom marshmallow_jsonapi import fields\nfrom marshmallow_jsonapi.flask import Relationship\n\nfrom app.api.helpers.exceptions import UnprocessableEntity\nfrom app.api.helpers.utilities import dasherize\nfrom app.api.schema.base import SoftDeletionSchema\nfrom app.models.access_code import AccessCode\nfrom utils.common import use_defaults\n\n\n@use_defaults()\nclass AccessCodeSchema(SoftDeletionSchema):\n    \"\"\"\n    Api schema for Access Code Model\n    \"\"\"\n\n    class Meta:\n        \"\"\"\n        Meta class for Access Code Api Schema\n        \"\"\"\n        type_ = 'access-code'\n        self_view = 'v1.access_code_detail'\n        self_view_kwargs = {'id': '<id>'}\n        inflect = dasherize\n\n    @validates_schema(pass_original=True)\n    def validate_date(self, data, original_data):\n        if 'id' in original_data['data']:\n            access_code = AccessCode.query.filter_by(id=original_data['data']['id']).one()\n\n            if 'valid_from' not in data:\n                data['valid_from'] = access_code.valid_from\n\n            if 'valid_till' not in data:\n                data['valid_till'] = access_code.valid_till\n\n        if data['valid_from'] > data['valid_till']:\n            raise UnprocessableEntity({'pointer': '/data/attributes/valid-till'},\n                                      \"valid_till should be after valid_from\")\n\n    @validates_schema(pass_original=True)\n    def validate_order_quantity(self, data, original_data):\n        if 'id' in original_data['data']:\n            access_code = AccessCode.query.filter_by(id=original_data['data']['id']).one()\n\n            if 'min_quantity' not in data:\n                data['min_quantity'] = access_code.min_quantity\n\n            if 'max_quantity' not in data:\n                data['max_quantity'] = access_code.max_quantity\n\n            if 'tickets_number' not in data:\n                data['tickets_number'] = access_code.tickets_number\n\n        min_quantity = data.get('min_quantity', None)\n        max_quantity = data.get('max_quantity', None)\n        if min_quantity is not None and max_quantity is not None:\n            if min_quantity > max_quantity:\n                raise UnprocessableEntity(\n                    {'pointer': '/data/attributes/min-quantity'},\n                    \"min-quantity should be less than max-quantity\"\n                )\n\n        if 'tickets_number' in data and 'max_quantity' in data:\n            if data['tickets_number'] < data['max_quantity']:\n                raise UnprocessableEntity({'pointer': '/data/attributes/tickets-number'},\n                                          \"tickets-number should be greater than max-quantity\")\n\n    id = fields.Integer(dump_ony=True)\n    code = fields.Str(required=True)\n    access_url = fields.Url(allow_none=True)\n    is_active = fields.Boolean(default=False)\n\n    # For event level access this holds the max. uses\n    tickets_number = fields.Integer(validate=lambda n: n >= 0, allow_none=True)\n\n    min_quantity = fields.Integer(validate=lambda n: n >= 0, allow_none=True)\n    max_quantity = fields.Integer(validate=lambda n: n >= 0, allow_none=True)\n    valid_from = fields.DateTime(required=True)\n    valid_till = fields.DateTime(required=True)\n    event = Relationship(attribute='event',\n                         self_view='v1.access_code_event',\n                         self_view_kwargs={'id': '<id>'},\n                         related_view='v1.event_detail',\n                         related_view_kwargs={'access_code_id': '<id>'},\n                         schema='EventSchemaPublic',\n                         type_='event')\n    marketer = Relationship(attribute='user',\n                            self_view='v1.access_code_user',\n                            self_view_kwargs={'id': '<id>'},\n                            related_view='v1.user_detail',\n                            related_view_kwargs={'access_code_id': '<id>'},\n                            schema='UserSchemaPublic',\n                            type_='user')\n    tickets = Relationship(attribute='tickets',\n                           self_view='v1.access_code_tickets',\n                           self_view_kwargs={'id': '<id>'},\n                           related_view='v1.ticket_list',\n                           related_view_kwargs={'access_code_id': '<id>'},\n                           schema='TicketSchemaPublic',\n                           many=True,\n                           type_='ticket')\n", "path": "app/api/schema/access_codes.py"}, {"content": "from flask_rest_jsonapi import ResourceDetail, ResourceList, ResourceRelationship\nfrom flask_rest_jsonapi.exceptions import ObjectNotFound\n\nfrom app.api.bootstrap import api\nfrom app.api.helpers.db import safe_query\nfrom app.api.helpers.exceptions import ForbiddenException, UnprocessableEntity\nfrom app.api.helpers.permission_manager import has_access\nfrom app.api.helpers.permissions import jwt_required\nfrom app.api.helpers.query import event_query\nfrom app.api.helpers.utilities import require_relationship\nfrom app.api.schema.access_codes import AccessCodeSchema\nfrom app.models import db\nfrom app.models.access_code import AccessCode\nfrom app.models.ticket import Ticket\nfrom app.models.user import User\n\n\nclass AccessCodeListPost(ResourceList):\n    \"\"\"\n    Create AccessCodes\n    \"\"\"\n    def before_post(self, args, kwargs, data):\n        \"\"\"\n        before post method to check for required relationships and permissions\n        :param args:\n        :param kwargs:\n        :param data:\n        :return:\n        \"\"\"\n        require_relationship(['event', 'user'], data)\n        if not has_access('is_coorganizer', event_id=data['event']):\n            raise ForbiddenException({'source': ''}, \"Minimum Organizer access required\")\n\n    schema = AccessCodeSchema\n    methods = ['POST', ]\n    data_layer = {'session': db.session,\n                  'model': AccessCode\n                  }\n\n\nclass AccessCodeList(ResourceList):\n    \"\"\"\n    List AccessCodes\n    \"\"\"\n    def query(self, view_kwargs):\n        \"\"\"\n        Method to get access codes list based on different view_kwargs\n        :param view_kwargs:\n        :return:\n        \"\"\"\n        query_ = self.session.query(AccessCode)\n        query_ = event_query(self, query_, view_kwargs, permission='is_coorganizer')\n        if view_kwargs.get('user_id'):\n            user = safe_query(self, User, 'id', view_kwargs['user_id'], 'user_id')\n            if not has_access('is_user_itself', user_id=user.id):\n                raise ForbiddenException({'source': ''}, 'Access Forbidden')\n            query_ = query_.join(User).filter(User.id == user.id)\n        if view_kwargs.get('ticket_id'):\n            ticket = safe_query(self, Ticket, 'id', view_kwargs['ticket_id'], 'ticket_id')\n            if not has_access('is_coorganizer', event_id=ticket.event_id):\n                raise ForbiddenException({'source': ''}, 'Access Forbidden')\n            # access_code - ticket :: many-to-many relationship\n            query_ = AccessCode.query.filter(AccessCode.tickets.any(id=ticket.id))\n            query_\n        return query_\n\n    view_kwargs = True\n    methods = ['GET', ]\n    schema = AccessCodeSchema\n    data_layer = {'session': db.session,\n                  'model': AccessCode,\n                  'methods': {\n                      'query': query,\n                  }}\n\n\nclass AccessCodeDetail(ResourceDetail):\n    \"\"\"\n    AccessCode detail by id or code\n    \"\"\"\n    def before_get(self, args, kwargs):\n        \"\"\"\n        before get method of access code details.\n        Check for permissions on the basis of kwargs.\n        :param args:\n        :param kwargs:\n        :return:\n        \"\"\"\n        # Any registered user can fetch access code details using the code.\n        if kwargs.get('code'):\n            access = db.session.query(AccessCode).filter_by(code=kwargs.get('code')).first()\n            if access:\n                kwargs['id'] = access.id\n            else:\n                raise ObjectNotFound({'parameter': '{code}'}, \"Access Code:  not found\")\n            return\n\n        # Co-organizer or the admin can fetch access code details using the id.\n        if kwargs.get('id'):\n            access = db.session.query(AccessCode).filter_by(id=kwargs.get('id')).one()\n            if not access:\n                raise ObjectNotFound({'parameter': '{id}'}, \"Access Code:  not found\")\n\n            if not has_access('is_coorganizer', event_id=access.event_id):\n                raise UnprocessableEntity({'source': ''},\n                                          \"Please verify your permission\")\n\n    decorators = (jwt_required, api.has_permission('is_coorganizer', fetch='event_id',\n                  fetch_as=\"event_id\", model=AccessCode, methods=\"PATCH\"),\n                  api.has_permission('is_coorganizer_but_not_admin', fetch='event_id',\n                  fetch_as=\"event_id\", model=AccessCode, methods=\"DELETE\"),)\n    schema = AccessCodeSchema\n    data_layer = {'session': db.session,\n                  'model': AccessCode\n                  }\n\n\nclass AccessCodeRelationshipRequired(ResourceRelationship):\n    \"\"\"\n    AccessCode Relationship Required\n    \"\"\"\n    decorators = (jwt_required,)\n    methods = ['GET', 'PATCH']\n    schema = AccessCodeSchema\n    data_layer = {'session': db.session,\n                  'model': AccessCode}\n\n\nclass AccessCodeRelationshipOptional(ResourceRelationship):\n    \"\"\"\n    AccessCode Relationship Optional\n    \"\"\"\n    decorators = (jwt_required,)\n    schema = AccessCodeSchema\n    data_layer = {'session': db.session,\n                  'model': AccessCode}\n", "path": "app/api/access_codes.py"}], "after_files": [{"content": "from marshmallow import validates_schema\nfrom marshmallow_jsonapi import fields\nfrom marshmallow_jsonapi.flask import Relationship\n\nfrom app.api.helpers.exceptions import UnprocessableEntity\nfrom app.api.helpers.utilities import dasherize\nfrom app.api.schema.base import SoftDeletionSchema\nfrom app.models.access_code import AccessCode\nfrom utils.common import use_defaults\n\n\n@use_defaults()\nclass AccessCodeSchema(SoftDeletionSchema):\n    \"\"\"\n    Api schema for Access Code Model\n    \"\"\"\n\n    class Meta:\n        \"\"\"\n        Meta class for Access Code Api Schema\n        \"\"\"\n        type_ = 'access-code'\n        self_view = 'v1.access_code_detail'\n        self_view_kwargs = {'id': '<id>'}\n        inflect = dasherize\n\n    @validates_schema(pass_original=True)\n    def validate_date(self, data, original_data):\n        if 'id' in original_data['data']:\n            access_code = AccessCode.query.filter_by(id=original_data['data']['id']).one()\n\n            if 'valid_from' not in data:\n                data['valid_from'] = access_code.valid_from\n\n            if 'valid_till' not in data:\n                data['valid_till'] = access_code.valid_till\n\n        if data['valid_from'] > data['valid_till']:\n            raise UnprocessableEntity({'pointer': '/data/attributes/valid-till'},\n                                      \"valid_till should be after valid_from\")\n\n    @validates_schema(pass_original=True)\n    def validate_order_quantity(self, data, original_data):\n        if 'id' in original_data['data']:\n            access_code = AccessCode.query.filter_by(id=original_data['data']['id']).one()\n\n            if 'min_quantity' not in data:\n                data['min_quantity'] = access_code.min_quantity\n\n            if 'max_quantity' not in data:\n                data['max_quantity'] = access_code.max_quantity\n\n            if 'tickets_number' not in data:\n                data['tickets_number'] = access_code.tickets_number\n\n        min_quantity = data.get('min_quantity', None)\n        max_quantity = data.get('max_quantity', None)\n        tickets_number = data.get('tickets_number', None)\n        if min_quantity and max_quantity and (min_quantity > max_quantity):\n            raise UnprocessableEntity(\n                    {'pointer': '/data/attributes/min-quantity'},\n                    \"min-quantity should be less than max-quantity\"\n            )\n\n        if tickets_number and max_quantity and (tickets_number < max_quantity):\n            raise UnprocessableEntity({'pointer': '/data/attributes/tickets-number'},\n                                      \"tickets-number should be greater than max-quantity\")\n\n    id = fields.Integer(dump_ony=True)\n    code = fields.Str(required=True)\n    access_url = fields.Url(allow_none=True)\n    is_active = fields.Boolean(default=False)\n\n    # For event level access this holds the max. uses\n    tickets_number = fields.Integer(validate=lambda n: n >= 0, allow_none=True)\n\n    min_quantity = fields.Integer(validate=lambda n: n >= 0, allow_none=True)\n    max_quantity = fields.Integer(validate=lambda n: n >= 0, allow_none=True)\n    valid_from = fields.DateTime(required=True)\n    valid_till = fields.DateTime(required=True)\n    event = Relationship(attribute='event',\n                         self_view='v1.access_code_event',\n                         self_view_kwargs={'id': '<id>'},\n                         related_view='v1.event_detail',\n                         related_view_kwargs={'access_code_id': '<id>'},\n                         schema='EventSchemaPublic',\n                         type_='event')\n    marketer = Relationship(attribute='user',\n                            self_view='v1.access_code_user',\n                            self_view_kwargs={'id': '<id>'},\n                            related_view='v1.user_detail',\n                            related_view_kwargs={'access_code_id': '<id>'},\n                            schema='UserSchemaPublic',\n                            type_='user')\n    tickets = Relationship(attribute='tickets',\n                           self_view='v1.access_code_tickets',\n                           self_view_kwargs={'id': '<id>'},\n                           related_view='v1.ticket_list',\n                           related_view_kwargs={'access_code_id': '<id>'},\n                           schema='TicketSchemaPublic',\n                           many=True,\n                           type_='ticket')\n", "path": "app/api/schema/access_codes.py"}, {"content": "from flask_rest_jsonapi import ResourceDetail, ResourceList, ResourceRelationship\nfrom flask_rest_jsonapi.exceptions import ObjectNotFound\nfrom sqlalchemy.orm.exc import NoResultFound\n\nfrom app.api.bootstrap import api\nfrom app.api.helpers.db import safe_query\nfrom app.api.helpers.exceptions import ForbiddenException, ConflictException\nfrom app.api.helpers.exceptions import UnprocessableEntity\nfrom app.api.helpers.permission_manager import has_access\nfrom app.api.helpers.permissions import jwt_required\nfrom app.api.helpers.query import event_query\nfrom app.api.helpers.utilities import require_relationship\nfrom app.api.schema.access_codes import AccessCodeSchema\nfrom app.models import db\nfrom app.models.access_code import AccessCode\nfrom app.models.ticket import Ticket\nfrom app.models.user import User\n\n\nclass AccessCodeListPost(ResourceList):\n    \"\"\"\n    Create AccessCodes\n    \"\"\"\n    def before_post(self, args, kwargs, data):\n        \"\"\"\n        before post method to check for required relationships and permissions\n        :param args:\n        :param kwargs:\n        :param data:\n        :return:\n        \"\"\"\n        require_relationship(['event', 'user'], data)\n        if not has_access('is_coorganizer', event_id=data['event']):\n            raise ForbiddenException({'source': ''}, \"Minimum Organizer access required\")\n\n    def before_create_object(self, data, view_kwargs):\n        \"\"\"\n        before create object method for AccessCodeListPost Class\n        :param data:\n        :param view_kwargs:\n        :return:\n        \"\"\"\n        if data.get('tickets', None):\n            for ticket in data['tickets']:\n                # Ensuring that the ticket exists and is hidden.\n                try:\n                    ticket_object = self.session.query(Ticket).filter_by(id=int(ticket),\n                                                                         deleted_at=None).one()\n                    if not ticket_object.is_hidden:\n                        raise ConflictException({'pointer': '/data/relationships/tickets'},\n                                                \"Ticket with id {} is public.\".format(ticket) +\n                                                \" Access code cannot be applied to public tickets\")\n                except NoResultFound:\n                    raise ConflictException({'pointer': '/data/relationships/tickets'},\n                                            \"Ticket with id {} does not exists\".format(str(ticket)))\n\n    schema = AccessCodeSchema\n    methods = ['POST', ]\n    data_layer = {'session': db.session,\n                  'model': AccessCode,\n                  'methods': {'before_create_object': before_create_object\n                              }}\n\n\nclass AccessCodeList(ResourceList):\n    \"\"\"\n    List AccessCodes\n    \"\"\"\n    def query(self, view_kwargs):\n        \"\"\"\n        Method to get access codes list based on different view_kwargs\n        :param view_kwargs:\n        :return:\n        \"\"\"\n        query_ = self.session.query(AccessCode)\n        query_ = event_query(self, query_, view_kwargs, permission='is_coorganizer')\n        if view_kwargs.get('user_id'):\n            user = safe_query(self, User, 'id', view_kwargs['user_id'], 'user_id')\n            if not has_access('is_user_itself', user_id=user.id):\n                raise ForbiddenException({'source': ''}, 'Access Forbidden')\n            query_ = query_.join(User).filter(User.id == user.id)\n        if view_kwargs.get('ticket_id'):\n            ticket = safe_query(self, Ticket, 'id', view_kwargs['ticket_id'], 'ticket_id')\n            if not has_access('is_coorganizer', event_id=ticket.event_id):\n                raise ForbiddenException({'source': ''}, 'Access Forbidden')\n            # access_code - ticket :: many-to-many relationship\n            query_ = AccessCode.query.filter(AccessCode.tickets.any(id=ticket.id))\n            query_\n        return query_\n\n    view_kwargs = True\n    methods = ['GET', ]\n    schema = AccessCodeSchema\n    data_layer = {'session': db.session,\n                  'model': AccessCode,\n                  'methods': {\n                      'query': query,\n                  }}\n\n\nclass AccessCodeDetail(ResourceDetail):\n    \"\"\"\n    AccessCode detail by id or code\n    \"\"\"\n    def before_get(self, args, kwargs):\n        \"\"\"\n        before get method of access code details.\n        Check for permissions on the basis of kwargs.\n        :param args:\n        :param kwargs:\n        :return:\n        \"\"\"\n        # Any registered user can fetch access code details using the code.\n        if kwargs.get('code'):\n            access = db.session.query(AccessCode).filter_by(code=kwargs.get('code')).first()\n            if access:\n                kwargs['id'] = access.id\n            else:\n                raise ObjectNotFound({'parameter': '{code}'}, \"Access Code:  not found\")\n            return\n\n        # Co-organizer or the admin can fetch access code details using the id.\n        if kwargs.get('id'):\n            access = db.session.query(AccessCode).filter_by(id=kwargs.get('id')).one()\n            if not access:\n                raise ObjectNotFound({'parameter': '{id}'}, \"Access Code:  not found\")\n\n            if not has_access('is_coorganizer', event_id=access.event_id):\n                raise UnprocessableEntity({'source': ''},\n                                          \"Please verify your permission\")\n\n    decorators = (jwt_required, api.has_permission('is_coorganizer', fetch='event_id',\n                  fetch_as=\"event_id\", model=AccessCode, methods=\"PATCH\"),\n                  api.has_permission('is_coorganizer_but_not_admin', fetch='event_id',\n                  fetch_as=\"event_id\", model=AccessCode, methods=\"DELETE\"),)\n    schema = AccessCodeSchema\n    data_layer = {'session': db.session,\n                  'model': AccessCode\n                  }\n\n\nclass AccessCodeRelationshipRequired(ResourceRelationship):\n    \"\"\"\n    AccessCode Relationship Required\n    \"\"\"\n    decorators = (jwt_required,)\n    methods = ['GET', 'PATCH']\n    schema = AccessCodeSchema\n    data_layer = {'session': db.session,\n                  'model': AccessCode}\n\n\nclass AccessCodeRelationshipOptional(ResourceRelationship):\n    \"\"\"\n    AccessCode Relationship Optional\n    \"\"\"\n    decorators = (jwt_required,)\n    schema = AccessCodeSchema\n    data_layer = {'session': db.session,\n                  'model': AccessCode}\n", "path": "app/api/access_codes.py"}]}