We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Admin Access required for accessing Order endpoint
**Describe the bug**
Admin access is required for endpoints related to Order. 

**To Reproduce**
GET/POST request to Order endpoints.

**Expected behavior**
The organizer should be able to query the Order endpoints as it was before.

**Stacktrace**
`{
    "errors": [
        {
            "status": 403,
            "source": {
                "source": ""
            },
            "title": "Access Forbidden",
            "detail": "Admin Access Required"
        }
    ],
    "jsonapi": {
        "version": "1.0"
    }
}`




--- 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/orders.py`
Content:
```
1 from datetime import datetime
2 
3 from flask import request, render_template
4 from flask_jwt import current_identity as current_user
5 from flask_rest_jsonapi import ResourceDetail, ResourceList, ResourceRelationship
6 from marshmallow_jsonapi import fields
7 from marshmallow_jsonapi.flask import Schema
8 
9 from app.api.data_layers.ChargesLayer import ChargesLayer
10 from app.api.helpers.db import save_to_db, safe_query
11 from app.api.helpers.exceptions import ForbiddenException, UnprocessableEntity
12 from app.api.helpers.files import create_save_pdf
13 from app.api.helpers.files import make_frontend_url
14 from app.api.helpers.mail import send_email_to_attendees
15 from app.api.helpers.mail import send_order_cancel_email
16 from app.api.helpers.notification import send_notif_to_attendees, send_notif_ticket_purchase_organizer, \
17     send_notif_ticket_cancel
18 from app.api.helpers.permission_manager import has_access
19 from app.api.helpers.permissions import jwt_required
20 from app.api.helpers.query import event_query
21 from app.api.helpers.ticketing import TicketingManager
22 from app.api.helpers.utilities import dasherize, require_relationship
23 from app.api.schema.orders import OrderSchema
24 from app.models import db
25 from app.models.discount_code import DiscountCode, TICKET
26 from app.models.order import Order, OrderTicket
27 from app.models.ticket_holder import TicketHolder
28 
29 
30 class OrdersListPost(ResourceList):
31     """
32     OrderListPost class for OrderSchema
33     """
34     def before_post(self, args, kwargs, data=None):
35         """
36         before post method to check for required relationship and proper permission
37         :param args:
38         :param kwargs:
39         :param data:
40         :return:
41         """
42         require_relationship(['event', 'ticket_holders'], data)
43         if not has_access('is_coorganizer', event_id=data['event']):
44             data['status'] = 'pending'
45 
46     def before_create_object(self, data, view_kwargs):
47         """
48         before create object method for OrderListPost Class
49         :param data:
50         :param view_kwargs:
51         :return:
52         """
53         if data.get('cancel_note'):
54             del data['cancel_note']
55 
56         # Apply discount only if the user is not event admin
57         if data.get('discount') and not has_access('is_coorganizer', event_id=data['event']):
58             discount_code = safe_query(self, DiscountCode, 'id', data['discount'], 'discount_code_id')
59             if not discount_code.is_active:
60                 raise UnprocessableEntity({'source': 'discount_code_id'}, "Inactive Discount Code")
61             else:
62                 now = datetime.utcnow()
63                 valid_from = datetime.strptime(discount_code.valid_from, '%Y-%m-%d %H:%M:%S')
64                 valid_till = datetime.strptime(discount_code.valid_till, '%Y-%m-%d %H:%M:%S')
65                 if not (valid_from <= now <= valid_till):
66                     raise UnprocessableEntity({'source': 'discount_code_id'}, "Inactive Discount Code")
67                 if not TicketingManager.match_discount_quantity(discount_code, data['ticket_holders']):
68                     raise UnprocessableEntity({'source': 'discount_code_id'}, 'Discount Usage Exceeded')
69 
70             if discount_code.event.id != data['event'] and discount_code.user_for == TICKET:
71                 raise UnprocessableEntity({'source': 'discount_code_id'}, "Invalid Discount Code")
72 
73     def after_create_object(self, order, data, view_kwargs):
74         """
75         after create object method for OrderListPost Class
76         :param order:
77         :param data:
78         :param view_kwargs:
79         :return:
80         """
81         order_tickets = {}
82         for holder in order.ticket_holders:
83             if holder.id != current_user.id:
84                 pdf = create_save_pdf(render_template('/pdf/ticket_attendee.html', order=order, holder=holder))
85             else:
86                 pdf = create_save_pdf(render_template('/pdf/ticket_purchaser.html', order=order))
87             holder.pdf_url = pdf
88             save_to_db(holder)
89             if order_tickets.get(holder.ticket_id) is None:
90                 order_tickets[holder.ticket_id] = 1
91             else:
92                 order_tickets[holder.ticket_id] += 1
93         for ticket in order_tickets:
94             od = OrderTicket(order_id=order.id, ticket_id=ticket, quantity=order_tickets[ticket])
95             save_to_db(od)
96         order.quantity = order.get_tickets_count()
97         save_to_db(order)
98         if not has_access('is_coorganizer', event_id=data['event']):
99             TicketingManager.calculate_update_amount(order)
100         send_email_to_attendees(order, current_user.id)
101         send_notif_to_attendees(order, current_user.id)
102 
103         order_url = make_frontend_url(path='/orders/{identifier}'.format(identifier=order.identifier))
104         for organizer in order.event.organizers:
105             send_notif_ticket_purchase_organizer(organizer, order.invoice_number, order_url, order.event.name)
106 
107         data['user_id'] = current_user.id
108 
109     methods = ['POST', ]
110     decorators = (jwt_required,)
111     schema = OrderSchema
112     data_layer = {'session': db.session,
113                   'model': Order,
114                   'methods': {'before_create_object': before_create_object,
115                               'after_create_object': after_create_object
116                               }}
117 
118 
119 class OrdersList(ResourceList):
120     """
121     OrderList class for OrderSchema
122     """
123     def before_get(self, args, kwargs):
124         """
125         before get method to get the resource id for fetching details
126         :param args:
127         :param kwargs:
128         :return:
129         """
130         if kwargs.get('event_id') is None:
131             if 'GET' in request.method and has_access('is_admin'):
132                 pass
133             else:
134                 raise ForbiddenException({'source': ''}, "Admin Access Required")
135         elif not has_access('is_coorganizer', event_id=kwargs['event_id']):
136             raise ForbiddenException({'source': ''}, "Co-Organizer Access Required")
137 
138     def query(self, view_kwargs):
139         query_ = self.session.query(Order)
140         query_ = event_query(self, query_, view_kwargs)
141 
142         return query_
143 
144     decorators = (jwt_required,)
145     methods = ['GET', ]
146     schema = OrderSchema
147     data_layer = {'session': db.session,
148                   'model': Order,
149                   'methods': {
150                       'query': query
151                   }}
152 
153 
154 class OrderDetail(ResourceDetail):
155     """
156     OrderDetail class for OrderSchema
157     """
158     def before_get_object(self, view_kwargs):
159         """
160         before get method to get the resource id for fetching details
161         :param view_kwargs:
162         :return:
163         """
164         if view_kwargs.get('attendee_id'):
165             attendee = safe_query(self, TicketHolder, 'id', view_kwargs['attendee_id'], 'attendee_id')
166             view_kwargs['order_identifier'] = attendee.order.identifier
167 
168         order = safe_query(self, Order, 'identifier', view_kwargs['order_identifier'], 'order_identifier')
169 
170         if not has_access('is_coorganizer_or_user_itself', event_id=order.event_id, user_id=order.user_id):
171             return ForbiddenException({'source': ''}, 'Access Forbidden')
172 
173     def before_update_object(self, order, data, view_kwargs):
174         """
175         :param order:
176         :param data:
177         :param view_kwargs:
178         :return:
179         """
180         if not has_access('is_admin'):
181             for element in data:
182                 if element != 'status':
183                     setattr(data, element, getattr(order, element))
184 
185         if not has_access('is_coorganizer', event_id=order.event.id):
186             raise ForbiddenException({'pointer': 'data/status'},
187                                      "To update status minimum Co-organizer access required")
188 
189     def after_update_object(self, order, data, view_kwargs):
190         """
191         :param order:
192         :param data:
193         :param view_kwargs:
194         :return:
195         """
196         if order.status == 'cancelled':
197             send_order_cancel_email(order)
198             send_notif_ticket_cancel(order)
199 
200     def before_delete_object(self, order, view_kwargs):
201         """
202         method to check for proper permissions for deleting
203         :param order:
204         :param view_kwargs:
205         :return:
206         """
207         if not has_access('is_coorganizer', event_id=order.event.id):
208             raise ForbiddenException({'source': ''}, 'Access Forbidden')
209 
210     decorators = (jwt_required,)
211 
212     schema = OrderSchema
213     data_layer = {'session': db.session,
214                   'model': Order,
215                   'url_field': 'order_identifier',
216                   'id_field': 'identifier',
217                   'methods': {
218                       'before_update_object': before_update_object,
219                       'before_delete_object': before_delete_object,
220                       'before_get_object': before_get_object,
221                       'after_update_object': after_update_object
222                   }}
223 
224 
225 class OrderRelationship(ResourceRelationship):
226     """
227     Order relationship
228     """
229     decorators = (jwt_required,)
230     schema = OrderSchema
231     data_layer = {'session': db.session,
232                   'model': Order}
233 
234 
235 class ChargeSchema(Schema):
236     """
237     ChargeSchema
238     """
239     class Meta:
240         """
241         Meta class for ChargeSchema
242         """
243         type_ = 'charge'
244         inflect = dasherize
245         self_view = 'v1.charge_list'
246         self_view_kwargs = {'id': '<id>'}
247 
248     id = fields.Str(dump_only=True)
249     stripe = fields.Str(allow_none=True)
250 
251 
252 class ChargeList(ResourceList):
253     """
254     ChargeList ResourceList for ChargesLayer class
255     """
256     methods = ['POST', ]
257     schema = ChargeSchema
258 
259     data_layer = {
260         'class': ChargesLayer,
261         'session': db.session
262     }
263
```
--- 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/orders.py b/app/api/orders.py
--- a/app/api/orders.py
+++ b/app/api/orders.py
@@ -127,11 +127,8 @@
         :param kwargs:
         :return:
         """
-        if kwargs.get('event_id') is None:
-            if 'GET' in request.method and has_access('is_admin'):
-                pass
-            else:
-                raise ForbiddenException({'source': ''}, "Admin Access Required")
+        if 'GET' in request.method and kwargs.get('event_id') is None:
+            pass
         elif not has_access('is_coorganizer', event_id=kwargs['event_id']):
             raise ForbiddenException({'source': ''}, "Co-Organizer Access Required")

{"golden_diff": "diff --git a/app/api/orders.py b/app/api/orders.py\n--- a/app/api/orders.py\n+++ b/app/api/orders.py\n@@ -127,11 +127,8 @@\n         :param kwargs:\n         :return:\n         \"\"\"\n-        if kwargs.get('event_id') is None:\n-            if 'GET' in request.method and has_access('is_admin'):\n-                pass\n-            else:\n-                raise ForbiddenException({'source': ''}, \"Admin Access Required\")\n+        if 'GET' in request.method and kwargs.get('event_id') is None:\n+            pass\n         elif not has_access('is_coorganizer', event_id=kwargs['event_id']):\n             raise ForbiddenException({'source': ''}, \"Co-Organizer Access Required\")\n", "issue": "Admin Access required for accessing Order endpoint\n**Describe the bug**\r\nAdmin access is required for endpoints related to Order. \r\n\r\n**To Reproduce**\r\nGET/POST request to Order endpoints.\r\n\r\n**Expected behavior**\r\nThe organizer should be able to query the Order endpoints as it was before.\r\n\r\n**Stacktrace**\r\n`{\r\n    \"errors\": [\r\n        {\r\n            \"status\": 403,\r\n            \"source\": {\r\n                \"source\": \"\"\r\n            },\r\n            \"title\": \"Access Forbidden\",\r\n            \"detail\": \"Admin Access Required\"\r\n        }\r\n    ],\r\n    \"jsonapi\": {\r\n        \"version\": \"1.0\"\r\n    }\r\n}`\r\n\r\n\r\n\n", "before_files": [{"content": "from datetime import datetime\n\nfrom flask import request, render_template\nfrom flask_jwt import current_identity as current_user\nfrom flask_rest_jsonapi import ResourceDetail, ResourceList, ResourceRelationship\nfrom marshmallow_jsonapi import fields\nfrom marshmallow_jsonapi.flask import Schema\n\nfrom app.api.data_layers.ChargesLayer import ChargesLayer\nfrom app.api.helpers.db import save_to_db, safe_query\nfrom app.api.helpers.exceptions import ForbiddenException, UnprocessableEntity\nfrom app.api.helpers.files import create_save_pdf\nfrom app.api.helpers.files import make_frontend_url\nfrom app.api.helpers.mail import send_email_to_attendees\nfrom app.api.helpers.mail import send_order_cancel_email\nfrom app.api.helpers.notification import send_notif_to_attendees, send_notif_ticket_purchase_organizer, \\\n    send_notif_ticket_cancel\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.ticketing import TicketingManager\nfrom app.api.helpers.utilities import dasherize, require_relationship\nfrom app.api.schema.orders import OrderSchema\nfrom app.models import db\nfrom app.models.discount_code import DiscountCode, TICKET\nfrom app.models.order import Order, OrderTicket\nfrom app.models.ticket_holder import TicketHolder\n\n\nclass OrdersListPost(ResourceList):\n    \"\"\"\n    OrderListPost class for OrderSchema\n    \"\"\"\n    def before_post(self, args, kwargs, data=None):\n        \"\"\"\n        before post method to check for required relationship and proper permission\n        :param args:\n        :param kwargs:\n        :param data:\n        :return:\n        \"\"\"\n        require_relationship(['event', 'ticket_holders'], data)\n        if not has_access('is_coorganizer', event_id=data['event']):\n            data['status'] = 'pending'\n\n    def before_create_object(self, data, view_kwargs):\n        \"\"\"\n        before create object method for OrderListPost Class\n        :param data:\n        :param view_kwargs:\n        :return:\n        \"\"\"\n        if data.get('cancel_note'):\n            del data['cancel_note']\n\n        # Apply discount only if the user is not event admin\n        if data.get('discount') and not has_access('is_coorganizer', event_id=data['event']):\n            discount_code = safe_query(self, DiscountCode, 'id', data['discount'], 'discount_code_id')\n            if not discount_code.is_active:\n                raise UnprocessableEntity({'source': 'discount_code_id'}, \"Inactive Discount Code\")\n            else:\n                now = datetime.utcnow()\n                valid_from = datetime.strptime(discount_code.valid_from, '%Y-%m-%d %H:%M:%S')\n                valid_till = datetime.strptime(discount_code.valid_till, '%Y-%m-%d %H:%M:%S')\n                if not (valid_from <= now <= valid_till):\n                    raise UnprocessableEntity({'source': 'discount_code_id'}, \"Inactive Discount Code\")\n                if not TicketingManager.match_discount_quantity(discount_code, data['ticket_holders']):\n                    raise UnprocessableEntity({'source': 'discount_code_id'}, 'Discount Usage Exceeded')\n\n            if discount_code.event.id != data['event'] and discount_code.user_for == TICKET:\n                raise UnprocessableEntity({'source': 'discount_code_id'}, \"Invalid Discount Code\")\n\n    def after_create_object(self, order, data, view_kwargs):\n        \"\"\"\n        after create object method for OrderListPost Class\n        :param order:\n        :param data:\n        :param view_kwargs:\n        :return:\n        \"\"\"\n        order_tickets = {}\n        for holder in order.ticket_holders:\n            if holder.id != current_user.id:\n                pdf = create_save_pdf(render_template('/pdf/ticket_attendee.html', order=order, holder=holder))\n            else:\n                pdf = create_save_pdf(render_template('/pdf/ticket_purchaser.html', order=order))\n            holder.pdf_url = pdf\n            save_to_db(holder)\n            if order_tickets.get(holder.ticket_id) is None:\n                order_tickets[holder.ticket_id] = 1\n            else:\n                order_tickets[holder.ticket_id] += 1\n        for ticket in order_tickets:\n            od = OrderTicket(order_id=order.id, ticket_id=ticket, quantity=order_tickets[ticket])\n            save_to_db(od)\n        order.quantity = order.get_tickets_count()\n        save_to_db(order)\n        if not has_access('is_coorganizer', event_id=data['event']):\n            TicketingManager.calculate_update_amount(order)\n        send_email_to_attendees(order, current_user.id)\n        send_notif_to_attendees(order, current_user.id)\n\n        order_url = make_frontend_url(path='/orders/{identifier}'.format(identifier=order.identifier))\n        for organizer in order.event.organizers:\n            send_notif_ticket_purchase_organizer(organizer, order.invoice_number, order_url, order.event.name)\n\n        data['user_id'] = current_user.id\n\n    methods = ['POST', ]\n    decorators = (jwt_required,)\n    schema = OrderSchema\n    data_layer = {'session': db.session,\n                  'model': Order,\n                  'methods': {'before_create_object': before_create_object,\n                              'after_create_object': after_create_object\n                              }}\n\n\nclass OrdersList(ResourceList):\n    \"\"\"\n    OrderList class for OrderSchema\n    \"\"\"\n    def before_get(self, args, kwargs):\n        \"\"\"\n        before get method to get the resource id for fetching details\n        :param args:\n        :param kwargs:\n        :return:\n        \"\"\"\n        if kwargs.get('event_id') is None:\n            if 'GET' in request.method and has_access('is_admin'):\n                pass\n            else:\n                raise ForbiddenException({'source': ''}, \"Admin Access Required\")\n        elif not has_access('is_coorganizer', event_id=kwargs['event_id']):\n            raise ForbiddenException({'source': ''}, \"Co-Organizer Access Required\")\n\n    def query(self, view_kwargs):\n        query_ = self.session.query(Order)\n        query_ = event_query(self, query_, view_kwargs)\n\n        return query_\n\n    decorators = (jwt_required,)\n    methods = ['GET', ]\n    schema = OrderSchema\n    data_layer = {'session': db.session,\n                  'model': Order,\n                  'methods': {\n                      'query': query\n                  }}\n\n\nclass OrderDetail(ResourceDetail):\n    \"\"\"\n    OrderDetail class for OrderSchema\n    \"\"\"\n    def before_get_object(self, view_kwargs):\n        \"\"\"\n        before get method to get the resource id for fetching details\n        :param view_kwargs:\n        :return:\n        \"\"\"\n        if view_kwargs.get('attendee_id'):\n            attendee = safe_query(self, TicketHolder, 'id', view_kwargs['attendee_id'], 'attendee_id')\n            view_kwargs['order_identifier'] = attendee.order.identifier\n\n        order = safe_query(self, Order, 'identifier', view_kwargs['order_identifier'], 'order_identifier')\n\n        if not has_access('is_coorganizer_or_user_itself', event_id=order.event_id, user_id=order.user_id):\n            return ForbiddenException({'source': ''}, 'Access Forbidden')\n\n    def before_update_object(self, order, data, view_kwargs):\n        \"\"\"\n        :param order:\n        :param data:\n        :param view_kwargs:\n        :return:\n        \"\"\"\n        if not has_access('is_admin'):\n            for element in data:\n                if element != 'status':\n                    setattr(data, element, getattr(order, element))\n\n        if not has_access('is_coorganizer', event_id=order.event.id):\n            raise ForbiddenException({'pointer': 'data/status'},\n                                     \"To update status minimum Co-organizer access required\")\n\n    def after_update_object(self, order, data, view_kwargs):\n        \"\"\"\n        :param order:\n        :param data:\n        :param view_kwargs:\n        :return:\n        \"\"\"\n        if order.status == 'cancelled':\n            send_order_cancel_email(order)\n            send_notif_ticket_cancel(order)\n\n    def before_delete_object(self, order, view_kwargs):\n        \"\"\"\n        method to check for proper permissions for deleting\n        :param order:\n        :param view_kwargs:\n        :return:\n        \"\"\"\n        if not has_access('is_coorganizer', event_id=order.event.id):\n            raise ForbiddenException({'source': ''}, 'Access Forbidden')\n\n    decorators = (jwt_required,)\n\n    schema = OrderSchema\n    data_layer = {'session': db.session,\n                  'model': Order,\n                  'url_field': 'order_identifier',\n                  'id_field': 'identifier',\n                  'methods': {\n                      'before_update_object': before_update_object,\n                      'before_delete_object': before_delete_object,\n                      'before_get_object': before_get_object,\n                      'after_update_object': after_update_object\n                  }}\n\n\nclass OrderRelationship(ResourceRelationship):\n    \"\"\"\n    Order relationship\n    \"\"\"\n    decorators = (jwt_required,)\n    schema = OrderSchema\n    data_layer = {'session': db.session,\n                  'model': Order}\n\n\nclass ChargeSchema(Schema):\n    \"\"\"\n    ChargeSchema\n    \"\"\"\n    class Meta:\n        \"\"\"\n        Meta class for ChargeSchema\n        \"\"\"\n        type_ = 'charge'\n        inflect = dasherize\n        self_view = 'v1.charge_list'\n        self_view_kwargs = {'id': '<id>'}\n\n    id = fields.Str(dump_only=True)\n    stripe = fields.Str(allow_none=True)\n\n\nclass ChargeList(ResourceList):\n    \"\"\"\n    ChargeList ResourceList for ChargesLayer class\n    \"\"\"\n    methods = ['POST', ]\n    schema = ChargeSchema\n\n    data_layer = {\n        'class': ChargesLayer,\n        'session': db.session\n    }\n", "path": "app/api/orders.py"}], "after_files": [{"content": "from datetime import datetime\n\nfrom flask import request, render_template\nfrom flask_jwt import current_identity as current_user\nfrom flask_rest_jsonapi import ResourceDetail, ResourceList, ResourceRelationship\nfrom marshmallow_jsonapi import fields\nfrom marshmallow_jsonapi.flask import Schema\n\nfrom app.api.data_layers.ChargesLayer import ChargesLayer\nfrom app.api.helpers.db import save_to_db, safe_query\nfrom app.api.helpers.exceptions import ForbiddenException, UnprocessableEntity\nfrom app.api.helpers.files import create_save_pdf\nfrom app.api.helpers.files import make_frontend_url\nfrom app.api.helpers.mail import send_email_to_attendees\nfrom app.api.helpers.mail import send_order_cancel_email\nfrom app.api.helpers.notification import send_notif_to_attendees, send_notif_ticket_purchase_organizer, \\\n    send_notif_ticket_cancel\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.ticketing import TicketingManager\nfrom app.api.helpers.utilities import dasherize, require_relationship\nfrom app.api.schema.orders import OrderSchema\nfrom app.models import db\nfrom app.models.discount_code import DiscountCode, TICKET\nfrom app.models.order import Order, OrderTicket\nfrom app.models.ticket_holder import TicketHolder\n\n\nclass OrdersListPost(ResourceList):\n    \"\"\"\n    OrderListPost class for OrderSchema\n    \"\"\"\n    def before_post(self, args, kwargs, data=None):\n        \"\"\"\n        before post method to check for required relationship and proper permission\n        :param args:\n        :param kwargs:\n        :param data:\n        :return:\n        \"\"\"\n        require_relationship(['event', 'ticket_holders'], data)\n        if not has_access('is_coorganizer', event_id=data['event']):\n            data['status'] = 'pending'\n\n    def before_create_object(self, data, view_kwargs):\n        \"\"\"\n        before create object method for OrderListPost Class\n        :param data:\n        :param view_kwargs:\n        :return:\n        \"\"\"\n        if data.get('cancel_note'):\n            del data['cancel_note']\n\n        # Apply discount only if the user is not event admin\n        if data.get('discount') and not has_access('is_coorganizer', event_id=data['event']):\n            discount_code = safe_query(self, DiscountCode, 'id', data['discount'], 'discount_code_id')\n            if not discount_code.is_active:\n                raise UnprocessableEntity({'source': 'discount_code_id'}, \"Inactive Discount Code\")\n            else:\n                now = datetime.utcnow()\n                valid_from = datetime.strptime(discount_code.valid_from, '%Y-%m-%d %H:%M:%S')\n                valid_till = datetime.strptime(discount_code.valid_till, '%Y-%m-%d %H:%M:%S')\n                if not (valid_from <= now <= valid_till):\n                    raise UnprocessableEntity({'source': 'discount_code_id'}, \"Inactive Discount Code\")\n                if not TicketingManager.match_discount_quantity(discount_code, data['ticket_holders']):\n                    raise UnprocessableEntity({'source': 'discount_code_id'}, 'Discount Usage Exceeded')\n\n            if discount_code.event.id != data['event'] and discount_code.user_for == TICKET:\n                raise UnprocessableEntity({'source': 'discount_code_id'}, \"Invalid Discount Code\")\n\n    def after_create_object(self, order, data, view_kwargs):\n        \"\"\"\n        after create object method for OrderListPost Class\n        :param order:\n        :param data:\n        :param view_kwargs:\n        :return:\n        \"\"\"\n        order_tickets = {}\n        for holder in order.ticket_holders:\n            if holder.id != current_user.id:\n                pdf = create_save_pdf(render_template('/pdf/ticket_attendee.html', order=order, holder=holder))\n            else:\n                pdf = create_save_pdf(render_template('/pdf/ticket_purchaser.html', order=order))\n            holder.pdf_url = pdf\n            save_to_db(holder)\n            if order_tickets.get(holder.ticket_id) is None:\n                order_tickets[holder.ticket_id] = 1\n            else:\n                order_tickets[holder.ticket_id] += 1\n        for ticket in order_tickets:\n            od = OrderTicket(order_id=order.id, ticket_id=ticket, quantity=order_tickets[ticket])\n            save_to_db(od)\n        order.quantity = order.get_tickets_count()\n        save_to_db(order)\n        if not has_access('is_coorganizer', event_id=data['event']):\n            TicketingManager.calculate_update_amount(order)\n        send_email_to_attendees(order, current_user.id)\n        send_notif_to_attendees(order, current_user.id)\n\n        order_url = make_frontend_url(path='/orders/{identifier}'.format(identifier=order.identifier))\n        for organizer in order.event.organizers:\n            send_notif_ticket_purchase_organizer(organizer, order.invoice_number, order_url, order.event.name)\n\n        data['user_id'] = current_user.id\n\n    methods = ['POST', ]\n    decorators = (jwt_required,)\n    schema = OrderSchema\n    data_layer = {'session': db.session,\n                  'model': Order,\n                  'methods': {'before_create_object': before_create_object,\n                              'after_create_object': after_create_object\n                              }}\n\n\nclass OrdersList(ResourceList):\n    \"\"\"\n    OrderList class for OrderSchema\n    \"\"\"\n    def before_get(self, args, kwargs):\n        \"\"\"\n        before get method to get the resource id for fetching details\n        :param args:\n        :param kwargs:\n        :return:\n        \"\"\"\n        if 'GET' in request.method and kwargs.get('event_id') is None:\n            pass\n        elif not has_access('is_coorganizer', event_id=kwargs['event_id']):\n            raise ForbiddenException({'source': ''}, \"Co-Organizer Access Required\")\n\n    def query(self, view_kwargs):\n        query_ = self.session.query(Order)\n        query_ = event_query(self, query_, view_kwargs)\n\n        return query_\n\n    decorators = (jwt_required,)\n    methods = ['GET', ]\n    schema = OrderSchema\n    data_layer = {'session': db.session,\n                  'model': Order,\n                  'methods': {\n                      'query': query\n                  }}\n\n\nclass OrderDetail(ResourceDetail):\n    \"\"\"\n    OrderDetail class for OrderSchema\n    \"\"\"\n    def before_get_object(self, view_kwargs):\n        \"\"\"\n        before get method to get the resource id for fetching details\n        :param view_kwargs:\n        :return:\n        \"\"\"\n        if view_kwargs.get('attendee_id'):\n            attendee = safe_query(self, TicketHolder, 'id', view_kwargs['attendee_id'], 'attendee_id')\n            view_kwargs['order_identifier'] = attendee.order.identifier\n\n        order = safe_query(self, Order, 'identifier', view_kwargs['order_identifier'], 'order_identifier')\n\n        if not has_access('is_coorganizer_or_user_itself', event_id=order.event_id, user_id=order.user_id):\n            return ForbiddenException({'source': ''}, 'Access Forbidden')\n\n    def before_update_object(self, order, data, view_kwargs):\n        \"\"\"\n        :param order:\n        :param data:\n        :param view_kwargs:\n        :return:\n        \"\"\"\n        if not has_access('is_admin'):\n            for element in data:\n                if element != 'status':\n                    setattr(data, element, getattr(order, element))\n\n        if not has_access('is_coorganizer', event_id=order.event.id):\n            raise ForbiddenException({'pointer': 'data/status'},\n                                     \"To update status minimum Co-organizer access required\")\n\n    def after_update_object(self, order, data, view_kwargs):\n        \"\"\"\n        :param order:\n        :param data:\n        :param view_kwargs:\n        :return:\n        \"\"\"\n        if order.status == 'cancelled':\n            send_order_cancel_email(order)\n            send_notif_ticket_cancel(order)\n\n    def before_delete_object(self, order, view_kwargs):\n        \"\"\"\n        method to check for proper permissions for deleting\n        :param order:\n        :param view_kwargs:\n        :return:\n        \"\"\"\n        if not has_access('is_coorganizer', event_id=order.event.id):\n            raise ForbiddenException({'source': ''}, 'Access Forbidden')\n\n    decorators = (jwt_required,)\n\n    schema = OrderSchema\n    data_layer = {'session': db.session,\n                  'model': Order,\n                  'url_field': 'order_identifier',\n                  'id_field': 'identifier',\n                  'methods': {\n                      'before_update_object': before_update_object,\n                      'before_delete_object': before_delete_object,\n                      'before_get_object': before_get_object,\n                      'after_update_object': after_update_object\n                  }}\n\n\nclass OrderRelationship(ResourceRelationship):\n    \"\"\"\n    Order relationship\n    \"\"\"\n    decorators = (jwt_required,)\n    schema = OrderSchema\n    data_layer = {'session': db.session,\n                  'model': Order}\n\n\nclass ChargeSchema(Schema):\n    \"\"\"\n    ChargeSchema\n    \"\"\"\n    class Meta:\n        \"\"\"\n        Meta class for ChargeSchema\n        \"\"\"\n        type_ = 'charge'\n        inflect = dasherize\n        self_view = 'v1.charge_list'\n        self_view_kwargs = {'id': '<id>'}\n\n    id = fields.Str(dump_only=True)\n    stripe = fields.Str(allow_none=True)\n\n\nclass ChargeList(ResourceList):\n    \"\"\"\n    ChargeList ResourceList for ChargesLayer class\n    \"\"\"\n    methods = ['POST', ]\n    schema = ChargeSchema\n\n    data_layer = {\n        'class': ChargesLayer,\n        'session': db.session\n    }\n", "path": "app/api/orders.py"}]}