We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Set attendees as required relationship to Orders API


--- 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
4 from flask_rest_jsonapi import ResourceDetail, ResourceList, ResourceRelationship
5 from marshmallow_jsonapi.flask import Schema, Relationship
6 from marshmallow_jsonapi import fields
7 from marshmallow import post_dump, validates_schema, validate
8 from flask_jwt import current_identity as current_user
9 
10 from app.api.bootstrap import api
11 from app.api.data_layers.ChargesLayer import ChargesLayer
12 from app.api.helpers.db import save_to_db, safe_query
13 from app.api.helpers.exceptions import ForbiddenException, UnprocessableEntity
14 from app.api.helpers.payment import PayPalPaymentsManager
15 from app.api.helpers.ticketing import TicketingManager
16 from app.api.helpers.permission_manager import has_access
17 from app.api.helpers.permissions import jwt_required
18 from app.api.helpers.utilities import dasherize, require_relationship
19 from app.models import db
20 from app.models.discount_code import DiscountCode, TICKET
21 from app.models.order import Order, OrderTicket
22 
23 
24 class OrderSchema(Schema):
25     class Meta:
26         type_ = 'order'
27         self_view = 'v1.order_detail'
28         self_view_kwargs = {'id': '<id>'}
29         inflect = dasherize
30 
31     @post_dump
32     def generate_payment_url(self, data):
33         if 'POST' in request.method or ('GET' in request.method and 'regenerate' in request.args) and 'completed' != \
34            data["status"]:
35             if data['payment_mode'] == 'stripe':
36                 data['payment_url'] = 'stripe://payment'
37             elif data['payment_mode'] == 'paypal':
38                 order = Order.query.filter_by(id=data['id']).first()
39                 data['payment_url'] = PayPalPaymentsManager.get_checkout_url(order)
40         return data
41 
42     @validates_schema
43     def initial_values(self, data):
44         if data.get('payment_mode') is None and 'POST' in request.method:
45             data['payment_mode'] = 'free'
46         return data
47 
48     id = fields.Str(dump_only=True)
49     identifier = fields.Str(dump_only=True)
50     amount = fields.Float(validate=lambda n: n > 0)
51     address = fields.Str()
52     city = fields.Str()
53     state = fields.Str(db.String)
54     country = fields.Str(required=True)
55     zipcode = fields.Str()
56     completed_at = fields.DateTime(dump_only=True)
57     transaction_id = fields.Str(dump_only=True)
58     payment_mode = fields.Str()
59     paid_via = fields.Str(dump_only=True)
60     brand = fields.Str(dump_only=True)
61     exp_month = fields.Str(dump_only=True)
62     exp_year = fields.Str(dump_only=True)
63     last4 = fields.Str(dump_only=True)
64     status = fields.Str(validate=validate.OneOf(choices=["pending", "cancelled", "confirmed", "deleted"]))
65     discount_code_id = fields.Str()
66     payment_url = fields.Str(dump_only=True)
67 
68     attendees = Relationship(attribute='ticket_holders',
69                              self_view='v1.order_attendee',
70                              self_view_kwargs={'identifier': '<identifier>'},
71                              related_view='v1.attendee_list',
72                              related_view_kwargs={'order_id': '<id>'},
73                              schema='AttendeeSchema',
74                              many=True,
75                              type_='attendee')
76 
77     tickets = Relationship(self_view='v1.order_ticket',
78                            self_view_kwargs={'identifier': '<identifier>'},
79                            related_view='v1.ticket_list',
80                            related_view_kwargs={'order_id': '<id>'},
81                            schema='TicketSchema',
82                            many=True,
83                            type_="ticket")
84 
85     user = Relationship(self_view='v1.order_user',
86                         self_view_kwargs={'identifier': '<identifier>'},
87                         related_view='v1.user_detail',
88                         related_view_kwargs={'id': '<user_id>'},
89                         schema='UserSchema',
90                         type_="user")
91 
92     event = Relationship(self_view='v1.order_event',
93                          self_view_kwargs={'identifier': '<identifier>'},
94                          related_view='v1.event_detail',
95                          related_view_kwargs={'id': '<event_id>'},
96                          schema='EventSchema',
97                          type_="event")
98 
99     marketer = Relationship(self_view='v1.order_marketer',
100                             self_view_kwargs={'identifier': '<identifier>'},
101                             related_view='v1.user_detail',
102                             related_view_kwargs={'id': '<marketer_id>'},
103                             schema='UserSchema',
104                             type_="user")
105 
106     discount_code = Relationship(self_view='v1.order_discount',
107                                  self_view_kwargs={'identifier': '<identifier>'},
108                                  related_view='v1.discount_code_detail',
109                                  related_view_kwargs={'id': '<discount_code_id>'},
110                                  schema='DiscountCodeSchema',
111                                  type_="discount-code")
112 
113 
114 class OrdersListPost(ResourceList):
115     def before_post(self, args, kwargs, data=None):
116         require_relationship(['event'], data)
117         if not has_access('is_coorganizer', event_id=data['event']):
118             data['status'] = 'pending'
119 
120     def before_create_object(self, data, view_kwargs):
121         # Apply discount only if the user is not event admin
122         if data.get('discount') and not has_access('is_coorganizer', event_id=data['event']):
123             discount_code = safe_query(self, DiscountCode, 'id', data['discount'], 'discount_code_id')
124             if not discount_code.is_active:
125                 raise UnprocessableEntity({'source': 'discount_code_id'}, "Inactive Discount Code")
126             else:
127                 now = datetime.utcnow()
128                 valid_from = datetime.strptime(discount_code.valid_from, '%Y-%m-%d %H:%M:%S')
129                 valid_till = datetime.strptime(discount_code.valid_till, '%Y-%m-%d %H:%M:%S')
130                 if not (valid_from <= now <= valid_till):
131                     raise UnprocessableEntity({'source': 'discount_code_id'}, "Inactive Discount Code")
132                 if not TicketingManager.match_discount_quantity(discount_code, data['ticket_holders']):
133                     raise UnprocessableEntity({'source': 'discount_code_id'}, 'Discount Usage Exceeded')
134 
135             if discount_code.event.id != data['event'] and discount_code.user_for == TICKET:
136                 raise UnprocessableEntity({'source': 'discount_code_id'}, "Invalid Discount Code")
137 
138     def after_create_object(self, order, data, view_kwargs):
139         order_tickets = {}
140         for holder in order.ticket_holders:
141             if order_tickets.get(holder.ticket_id) is None:
142                 order_tickets[holder.ticket_id] = 1
143             else:
144                 order_tickets[holder.ticket_id] += 1
145         for ticket in order_tickets:
146             od = OrderTicket(order_id=order.id, ticket_id=ticket, quantity=order_tickets[ticket])
147             save_to_db(od)
148         order.quantity = order.get_tickets_count()
149         save_to_db(order)
150         if not has_access('is_coorganizer', **view_kwargs):
151             TicketingManager.calculate_update_amount(order)
152 
153         data['user_id'] = current_user.id
154 
155     methods = ['POST', ]
156     decorators = (jwt_required,)
157     schema = OrderSchema
158     data_layer = {'session': db.session,
159                   'model': Order,
160                   'methods': {'before_create_object': before_create_object,
161                               'after_create_object': after_create_object
162                               }}
163 
164 
165 class OrdersList(ResourceList):
166     def before_get(self, args, kwargs):
167         if kwargs.get('event_id') is None:
168             if 'GET' in request.method and has_access('is_admin'):
169                 pass
170             else:
171                 raise ForbiddenException({'source': ''}, "Admin Access Required")
172         elif not has_access('is_coorganizer', event_id=kwargs['event_id']):
173             raise ForbiddenException({'source': ''}, "Co-Organizer Access Required")
174 
175     decorators = (jwt_required,)
176     schema = OrderSchema
177     data_layer = {'session': db.session,
178                   'model': Order}
179 
180 
181 class OrderDetail(ResourceDetail):
182     def before_get_object(self, view_kwargs):
183         if view_kwargs.get('identifier'):
184             order = safe_query(self, Order, 'identifier', view_kwargs['identifier'], 'order_identifier')
185             view_kwargs['id'] = order.id
186 
187     def before_update_object(self, order, data, view_kwargs):
188         if data.get('status'):
189             if has_access('is_coorganizer', event_id=order.event.id):
190                 pass
191             else:
192                 raise ForbiddenException({'pointer': 'data/status'},
193                                          "To update status minimum Co-organizer access required")
194 
195     decorators = (api.has_permission('is_coorganizer', fetch="event_id", fetch_as="event_id", model=Order),)
196 
197     schema = OrderSchema
198     data_layer = {'session': db.session,
199                   'model': Order,
200                   'methods': {'before_update_object': before_update_object}}
201 
202 
203 class OrderRelationship(ResourceRelationship):
204     decorators = (jwt_required,)
205     schema = OrderSchema
206     data_layer = {'session': db.session,
207                   'model': Order}
208 
209 
210 class ChargeSchema(Schema):
211     class Meta:
212         type_ = 'charge'
213         inflect = dasherize
214         self_view = 'v1.charge_list'
215         self_view_kwargs = {'id': '<id>'}
216 
217     id = fields.Str(dump_only=True)
218     stripe = fields.Str(allow_none=True)
219 
220 
221 class ChargeList(ResourceList):
222     methods = ['POST', ]
223     schema = ChargeSchema
224 
225     data_layer = {
226         'class': ChargesLayer,
227         'session': db.session
228     }
229
```
--- 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
@@ -113,7 +113,7 @@
 
 class OrdersListPost(ResourceList):
     def before_post(self, args, kwargs, data=None):
-        require_relationship(['event'], data)
+        require_relationship(['event', 'attendees'], data)
         if not has_access('is_coorganizer', event_id=data['event']):
             data['status'] = 'pending'

{"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@@ -113,7 +113,7 @@\n \n class OrdersListPost(ResourceList):\n     def before_post(self, args, kwargs, data=None):\n-        require_relationship(['event'], data)\n+        require_relationship(['event', 'attendees'], data)\n         if not has_access('is_coorganizer', event_id=data['event']):\n             data['status'] = 'pending'\n", "issue": "Set attendees as required relationship to Orders API\n\n", "before_files": [{"content": "from datetime import datetime\n\nfrom flask import request\nfrom flask_rest_jsonapi import ResourceDetail, ResourceList, ResourceRelationship\nfrom marshmallow_jsonapi.flask import Schema, Relationship\nfrom marshmallow_jsonapi import fields\nfrom marshmallow import post_dump, validates_schema, validate\nfrom flask_jwt import current_identity as current_user\n\nfrom app.api.bootstrap import api\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.payment import PayPalPaymentsManager\nfrom app.api.helpers.ticketing import TicketingManager\nfrom app.api.helpers.permission_manager import has_access\nfrom app.api.helpers.permissions import jwt_required\nfrom app.api.helpers.utilities import dasherize, require_relationship\nfrom app.models import db\nfrom app.models.discount_code import DiscountCode, TICKET\nfrom app.models.order import Order, OrderTicket\n\n\nclass OrderSchema(Schema):\n    class Meta:\n        type_ = 'order'\n        self_view = 'v1.order_detail'\n        self_view_kwargs = {'id': '<id>'}\n        inflect = dasherize\n\n    @post_dump\n    def generate_payment_url(self, data):\n        if 'POST' in request.method or ('GET' in request.method and 'regenerate' in request.args) and 'completed' != \\\n           data[\"status\"]:\n            if data['payment_mode'] == 'stripe':\n                data['payment_url'] = 'stripe://payment'\n            elif data['payment_mode'] == 'paypal':\n                order = Order.query.filter_by(id=data['id']).first()\n                data['payment_url'] = PayPalPaymentsManager.get_checkout_url(order)\n        return data\n\n    @validates_schema\n    def initial_values(self, data):\n        if data.get('payment_mode') is None and 'POST' in request.method:\n            data['payment_mode'] = 'free'\n        return data\n\n    id = fields.Str(dump_only=True)\n    identifier = fields.Str(dump_only=True)\n    amount = fields.Float(validate=lambda n: n > 0)\n    address = fields.Str()\n    city = fields.Str()\n    state = fields.Str(db.String)\n    country = fields.Str(required=True)\n    zipcode = fields.Str()\n    completed_at = fields.DateTime(dump_only=True)\n    transaction_id = fields.Str(dump_only=True)\n    payment_mode = fields.Str()\n    paid_via = fields.Str(dump_only=True)\n    brand = fields.Str(dump_only=True)\n    exp_month = fields.Str(dump_only=True)\n    exp_year = fields.Str(dump_only=True)\n    last4 = fields.Str(dump_only=True)\n    status = fields.Str(validate=validate.OneOf(choices=[\"pending\", \"cancelled\", \"confirmed\", \"deleted\"]))\n    discount_code_id = fields.Str()\n    payment_url = fields.Str(dump_only=True)\n\n    attendees = Relationship(attribute='ticket_holders',\n                             self_view='v1.order_attendee',\n                             self_view_kwargs={'identifier': '<identifier>'},\n                             related_view='v1.attendee_list',\n                             related_view_kwargs={'order_id': '<id>'},\n                             schema='AttendeeSchema',\n                             many=True,\n                             type_='attendee')\n\n    tickets = Relationship(self_view='v1.order_ticket',\n                           self_view_kwargs={'identifier': '<identifier>'},\n                           related_view='v1.ticket_list',\n                           related_view_kwargs={'order_id': '<id>'},\n                           schema='TicketSchema',\n                           many=True,\n                           type_=\"ticket\")\n\n    user = Relationship(self_view='v1.order_user',\n                        self_view_kwargs={'identifier': '<identifier>'},\n                        related_view='v1.user_detail',\n                        related_view_kwargs={'id': '<user_id>'},\n                        schema='UserSchema',\n                        type_=\"user\")\n\n    event = Relationship(self_view='v1.order_event',\n                         self_view_kwargs={'identifier': '<identifier>'},\n                         related_view='v1.event_detail',\n                         related_view_kwargs={'id': '<event_id>'},\n                         schema='EventSchema',\n                         type_=\"event\")\n\n    marketer = Relationship(self_view='v1.order_marketer',\n                            self_view_kwargs={'identifier': '<identifier>'},\n                            related_view='v1.user_detail',\n                            related_view_kwargs={'id': '<marketer_id>'},\n                            schema='UserSchema',\n                            type_=\"user\")\n\n    discount_code = Relationship(self_view='v1.order_discount',\n                                 self_view_kwargs={'identifier': '<identifier>'},\n                                 related_view='v1.discount_code_detail',\n                                 related_view_kwargs={'id': '<discount_code_id>'},\n                                 schema='DiscountCodeSchema',\n                                 type_=\"discount-code\")\n\n\nclass OrdersListPost(ResourceList):\n    def before_post(self, args, kwargs, data=None):\n        require_relationship(['event'], 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        # 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        order_tickets = {}\n        for holder in order.ticket_holders:\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', **view_kwargs):\n            TicketingManager.calculate_update_amount(order)\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    def before_get(self, args, kwargs):\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    decorators = (jwt_required,)\n    schema = OrderSchema\n    data_layer = {'session': db.session,\n                  'model': Order}\n\n\nclass OrderDetail(ResourceDetail):\n    def before_get_object(self, view_kwargs):\n        if view_kwargs.get('identifier'):\n            order = safe_query(self, Order, 'identifier', view_kwargs['identifier'], 'order_identifier')\n            view_kwargs['id'] = order.id\n\n    def before_update_object(self, order, data, view_kwargs):\n        if data.get('status'):\n            if has_access('is_coorganizer', event_id=order.event.id):\n                pass\n            else:\n                raise ForbiddenException({'pointer': 'data/status'},\n                                         \"To update status minimum Co-organizer access required\")\n\n    decorators = (api.has_permission('is_coorganizer', fetch=\"event_id\", fetch_as=\"event_id\", model=Order),)\n\n    schema = OrderSchema\n    data_layer = {'session': db.session,\n                  'model': Order,\n                  'methods': {'before_update_object': before_update_object}}\n\n\nclass OrderRelationship(ResourceRelationship):\n    decorators = (jwt_required,)\n    schema = OrderSchema\n    data_layer = {'session': db.session,\n                  'model': Order}\n\n\nclass ChargeSchema(Schema):\n    class Meta:\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    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\nfrom flask_rest_jsonapi import ResourceDetail, ResourceList, ResourceRelationship\nfrom marshmallow_jsonapi.flask import Schema, Relationship\nfrom marshmallow_jsonapi import fields\nfrom marshmallow import post_dump, validates_schema, validate\nfrom flask_jwt import current_identity as current_user\n\nfrom app.api.bootstrap import api\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.payment import PayPalPaymentsManager\nfrom app.api.helpers.ticketing import TicketingManager\nfrom app.api.helpers.permission_manager import has_access\nfrom app.api.helpers.permissions import jwt_required\nfrom app.api.helpers.utilities import dasherize, require_relationship\nfrom app.models import db\nfrom app.models.discount_code import DiscountCode, TICKET\nfrom app.models.order import Order, OrderTicket\n\n\nclass OrderSchema(Schema):\n    class Meta:\n        type_ = 'order'\n        self_view = 'v1.order_detail'\n        self_view_kwargs = {'id': '<id>'}\n        inflect = dasherize\n\n    @post_dump\n    def generate_payment_url(self, data):\n        if 'POST' in request.method or ('GET' in request.method and 'regenerate' in request.args) and 'completed' != \\\n           data[\"status\"]:\n            if data['payment_mode'] == 'stripe':\n                data['payment_url'] = 'stripe://payment'\n            elif data['payment_mode'] == 'paypal':\n                order = Order.query.filter_by(id=data['id']).first()\n                data['payment_url'] = PayPalPaymentsManager.get_checkout_url(order)\n        return data\n\n    @validates_schema\n    def initial_values(self, data):\n        if data.get('payment_mode') is None and 'POST' in request.method:\n            data['payment_mode'] = 'free'\n        return data\n\n    id = fields.Str(dump_only=True)\n    identifier = fields.Str(dump_only=True)\n    amount = fields.Float(validate=lambda n: n > 0)\n    address = fields.Str()\n    city = fields.Str()\n    state = fields.Str(db.String)\n    country = fields.Str(required=True)\n    zipcode = fields.Str()\n    completed_at = fields.DateTime(dump_only=True)\n    transaction_id = fields.Str(dump_only=True)\n    payment_mode = fields.Str()\n    paid_via = fields.Str(dump_only=True)\n    brand = fields.Str(dump_only=True)\n    exp_month = fields.Str(dump_only=True)\n    exp_year = fields.Str(dump_only=True)\n    last4 = fields.Str(dump_only=True)\n    status = fields.Str(validate=validate.OneOf(choices=[\"pending\", \"cancelled\", \"confirmed\", \"deleted\"]))\n    discount_code_id = fields.Str()\n    payment_url = fields.Str(dump_only=True)\n\n    attendees = Relationship(attribute='ticket_holders',\n                             self_view='v1.order_attendee',\n                             self_view_kwargs={'identifier': '<identifier>'},\n                             related_view='v1.attendee_list',\n                             related_view_kwargs={'order_id': '<id>'},\n                             schema='AttendeeSchema',\n                             many=True,\n                             type_='attendee')\n\n    tickets = Relationship(self_view='v1.order_ticket',\n                           self_view_kwargs={'identifier': '<identifier>'},\n                           related_view='v1.ticket_list',\n                           related_view_kwargs={'order_id': '<id>'},\n                           schema='TicketSchema',\n                           many=True,\n                           type_=\"ticket\")\n\n    user = Relationship(self_view='v1.order_user',\n                        self_view_kwargs={'identifier': '<identifier>'},\n                        related_view='v1.user_detail',\n                        related_view_kwargs={'id': '<user_id>'},\n                        schema='UserSchema',\n                        type_=\"user\")\n\n    event = Relationship(self_view='v1.order_event',\n                         self_view_kwargs={'identifier': '<identifier>'},\n                         related_view='v1.event_detail',\n                         related_view_kwargs={'id': '<event_id>'},\n                         schema='EventSchema',\n                         type_=\"event\")\n\n    marketer = Relationship(self_view='v1.order_marketer',\n                            self_view_kwargs={'identifier': '<identifier>'},\n                            related_view='v1.user_detail',\n                            related_view_kwargs={'id': '<marketer_id>'},\n                            schema='UserSchema',\n                            type_=\"user\")\n\n    discount_code = Relationship(self_view='v1.order_discount',\n                                 self_view_kwargs={'identifier': '<identifier>'},\n                                 related_view='v1.discount_code_detail',\n                                 related_view_kwargs={'id': '<discount_code_id>'},\n                                 schema='DiscountCodeSchema',\n                                 type_=\"discount-code\")\n\n\nclass OrdersListPost(ResourceList):\n    def before_post(self, args, kwargs, data=None):\n        require_relationship(['event', 'attendees'], 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        # 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        order_tickets = {}\n        for holder in order.ticket_holders:\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', **view_kwargs):\n            TicketingManager.calculate_update_amount(order)\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    def before_get(self, args, kwargs):\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    decorators = (jwt_required,)\n    schema = OrderSchema\n    data_layer = {'session': db.session,\n                  'model': Order}\n\n\nclass OrderDetail(ResourceDetail):\n    def before_get_object(self, view_kwargs):\n        if view_kwargs.get('identifier'):\n            order = safe_query(self, Order, 'identifier', view_kwargs['identifier'], 'order_identifier')\n            view_kwargs['id'] = order.id\n\n    def before_update_object(self, order, data, view_kwargs):\n        if data.get('status'):\n            if has_access('is_coorganizer', event_id=order.event.id):\n                pass\n            else:\n                raise ForbiddenException({'pointer': 'data/status'},\n                                         \"To update status minimum Co-organizer access required\")\n\n    decorators = (api.has_permission('is_coorganizer', fetch=\"event_id\", fetch_as=\"event_id\", model=Order),)\n\n    schema = OrderSchema\n    data_layer = {'session': db.session,\n                  'model': Order,\n                  'methods': {'before_update_object': before_update_object}}\n\n\nclass OrderRelationship(ResourceRelationship):\n    decorators = (jwt_required,)\n    schema = OrderSchema\n    data_layer = {'session': db.session,\n                  'model': Order}\n\n\nclass ChargeSchema(Schema):\n    class Meta:\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    methods = ['POST', ]\n    schema = ChargeSchema\n\n    data_layer = {\n        'class': ChargesLayer,\n        'session': db.session\n    }\n", "path": "app/api/orders.py"}]}