def patch(self, ticket_id): """ Update a single ticket """ # To do check if ticket is admin schema = TicketSchema(partial=True) update_data = request.get_json() validated_update_data, errors = schema.load(update_data) if errors: return dict(status="fail", message=errors), 400 ticket = Ticket.get_by_id(ticket_id) if not ticket: return dict(status="fail", message=f"Ticket with id {ticket_id} not found"), 404 updated_ticket = Ticket.update(ticket, **validated_update_data) if not updated_ticket: return dict(status='fail', message='Internal Server Error'), 500 return dict(status="success", message="Ticket updated successfully"), 200
def create(self, payloads): self.model_ticket = Ticket() self.model_ticket.ticket_type = payloads['ticket_type'] self.model_ticket.price = payloads['price'] self.model_ticket.information = payloads['information'] self.model_ticket.type = payloads['type'] self.model_ticket.usd_price = payloads['usd_price'] if payloads['type'] == TICKET_TYPES['exhibitor']: if payloads['proposal_url']: proposal_url = self.save_file( payloads['proposal_url'] ) if payloads['proposal_url'] is not None else None self.model_ticket.proposal_url = proposal_url db.session.add(self.model_ticket) try: db.session.commit() data = self.model_ticket.as_dict() if payloads['type'] == TICKET_TYPES['exhibitor'] and data[ 'proposal_url']: data['proposal_url'] = Helper().url_helper( data['proposal_url'], current_app.config['GET_PROPOSAL_DOC_DEST']) print(data['proposal_url']) return {'error': False, 'data': data} except SQLAlchemyError as e: data = e.orig.args return {'error': True, 'data': data}
def get(current_user, workspaceId, projectId): """ Get Tickets """ pageNum = int(request.args.get('pageNum', 1)) itemsPerPage = int(request.args.get('itemsPerPage', 25)) tickets_list = Ticket.get_tickets(pageNum, itemsPerPage, projectId) totalItems = Ticket.get_total(projectId) displayName = { "id": "ID", "status": "Status", "category": "Category", "channel": "Channel", "name": "Name", "phone": "Phone", "email": "Email", "modifiedBy": "Modified By", "createdOn": "Created On", "lastModified": "Last Modified", } return { "tickets": tickets_list, "displayName": json.dumps(displayName), "pageNum": pageNum, "totalPages": math.ceil(totalItems / itemsPerPage), "totalEntries": totalItems }
def complete(self): serving_urls = [] sell_tickets = json.loads(self.request.body) event_key = self.util.decode_key(sell_tickets['event']).get() account = self.util.decode_key(sell_tickets['scalper_name']).get() uploads = self.components.upload.get_uploads() files = uploads.get('file') for blobinfo in files: logging.info('===::sell_tickets::=== %s' % type(account)) params = { 'event': event_key.key.urlsafe(), 'scalper_name': account.key, 'ticket_img': blobinfo.key(), 'section': sell_tickets['section'], 'quantity': sell_tickets['quantity'], 'price': sell_tickets['price'] } Ticket.create(params) # serving_urls.append({'filename': blobinfo.filename, # 'url': "https://storage.googleapis.com/%s" % (blobinfo.cloud_storage.gs_object_name[4:]), # 'content_type': blobinfo.content_type # }) return 200
def __get_customer_tickets(self, customer_id, filter_opt): """Get customer tickets filtered by order date or event date.""" try: tickets = [] order_date = filter_opt.get('order_date') event_date = filter_opt.get('event_date') if order_date: ticket_models = ( TicketModel.select().join(CustomerModel).where( CustomerModel.id == customer_id, TicketModel.order_date == order_date)) elif event_date: ticket_models = (TicketModel.select().join( CustomerModel).switch(TicketModel).join(EventModel).where( CustomerModel.id == customer_id, EventModel.date == event_date)) else: ticket_models = ( TicketModel.select().join(CustomerModel).where( CustomerModel.id == customer_id)) for ticket_model in ticket_models: ticket = Ticket.from_model(ticket_model) tickets.append(ticket) return tickets except DoesNotExist: raise DbActorError("Customer not found.", 404) from DoesNotExist
def create_ticket(self, flight_seat_id, ticket_no, status, user_id): ticket = Ticket(flight_seat_id=flight_seat_id, ticket_no=ticket_no, status=status, user_id=user_id) ticket.save() return ticket
def add_ticket(): form = AddTicketForm(request.form) if request.method == 'POST': # and form.validate(): with db.auto_commit(): ticket = Ticket() ticket.set_attrs(form.data) db.session.add(ticket) return redirect(url_for('admin.add_ticket')) return render_template('admin/TicketAdd.html', form=form)
def api_create(self): sell_tickets = json.loads(self.request.body) event_key = self.util.decode_key(sell_tickets['event']).get() account = self.util.decode_key(sell_tickets['scalper_name']).get() params = { 'event': event_key.key.urlsafe(), 'scalper_name': account.key, 'section': sell_tickets['section'], 'quantity': sell_tickets['quantity'], 'price': sell_tickets['price'] } Ticket.create(params) return 200
def get_event_ticket(): set_settings(paypal_mode='sandbox', paypal_sandbox_username=environ.get('PAYPAL_SANDBOX_USERNAME', 'SQPTVKtS8YvItGQuvHFvwve4'), paypal_sandbox_password=environ.get('PAYPAL_SANDBOX_PASSWORD', 'SQPTVKtS8YvItGQuvHFvwve4'), paypal_sandbox_signature=environ.get('PAYPAL_SANDBOX_SIGNATURE', 'SQPTVKtS8YvItGQuvHFvwve4'), secret='super secret key') event = ObjectMother.get_event() event.name = 'Super Event' event.state = 'Published' event.paypal_email = '*****@*****.**' save_to_db(event, "Event Saved") stripe_auth = StripeAuthorization( stripe_secret_key=environ.get('STRIPE_SECRET_KEY', 'sk_test_SQPTVKtS8YvItGQuvHFvwve4'), stripe_refresh_token=environ.get('STRIPE_REFRESH_TOKEN', 'sk_test_SQPTVKtS8YvItGQuvHFvwve4'), stripe_publishable_key=environ.get('STRIPE_PUBLISHABLE_KEY', 'pk_test_e2jsd4RNUlYesCUb2KJ9nkCm'), stripe_user_id=environ.get('STRIPE_USER_ID', '1445522255'), stripe_email=environ.get('STRIPE_EMAIL', '*****@*****.**'), event_id=event.id ) save_to_db(stripe_auth, "StripeAuthorization Saved") ticket = Ticket(name='Test Ticket', type='paid', sales_start=datetime.now() - timedelta(days=5), sales_end=datetime.now() + timedelta(days=5), description="SomeTicket", event=event, price=50) save_to_db(ticket, "Ticket Saved") save_to_db(Module(ticket_include=True, payment_include=True, donation_include=True)) return event, ticket
def remove(current_user, workspaceId, projectId): """ Remove Ticket By Id """ if request.content_type == 'application/json': post_data = request.get_json() if 'id' not in post_data: return response('failed', 'Ticket Id required', 402) else: ticket = Ticket.get_by_id(post_data.get('id')) if ticket: ticket.delete_ticket(current_user) res_payload = { 'id': ticket._id, 'firstName': ticket.firstName, 'lastName': ticket.lastName, 'category': ticket.category, 'status': ticket.status, 'notes': ticket.notes, 'channel': ticket.channel, 'createdOn': ticket.createdOn, 'phone': ticket.phone, 'email': ticket.email } return response_with_obj('success', 'Ticket deleted successfully', res_payload, 200) else: response('failed', 'Ticket not found', 402) else: return response('failed', 'Content-type must be json', 402)
def get_categories(current_user, workspaceId, projectId): """ Get all Categories in Tickets """ categories = Ticket.get_categories(projectId) return {"categories": categories}
def test_valid_id(): ticket = Ticket(title='test', creator="*****@*****.**", created=datetime.now()) ticket.save() abort_if_ticket_id_invalid(ticket.id) ticket.delete()
def __purchase_event_ticket(self, customer_id, event_id, quantity): """Purchase of a certain number of tickets for a specific event.""" try: event_model = EventModel.get(EventModel.id == event_id) except DoesNotExist: raise DbActorError("Event not found.", 404) from DoesNotExist customer_model = CustomerModel.get(CustomerModel.id == customer_id) event_customer_ticket_models = (TicketModel.select().join( CustomerModel).switch(TicketModel).join(EventModel).where( CustomerModel.id == customer_id, EventModel.id == event_id)) event_ticket_models = (TicketModel.select().join(EventModel).where( EventModel.id == event_id)) total_price = event_model.ticket_price * quantity available_budget = self.__get_customer_budget(customer_model.id, event_model.date.year) if available_budget - total_price < 0: raise DbActorError("The budget of the customer is not sufficient.", 400) if event_model.max_tickets_per_customer < len( event_customer_ticket_models) + quantity: raise DbActorError( ("With this purchase the maximum number of tickets per " "customer for this event would be exceeded."), 400) if event_model.max_tickets < len(event_ticket_models) + quantity: raise DbActorError(("With this purchase the maximum number of " "tickets for this event would be exceeded."), 400) sale_not_started = event_model.sale_start_date > date.today() sale_end_date = event_model.sale_start_date + \ timedelta(days=event_model.sale_period) sale_over = sale_end_date < date.today() if sale_not_started or sale_over: raise DbActorError( "Currently no tickets can be purchased for this event.", 400) for _ in range(quantity): ticket_model = TicketModel(order_date=date.today(), customer=customer_model, event=event_model) ticket_model.save()
def add(current_user, workspaceId, projectId): """ Create Tickets """ if request.content_type == 'application/json': post_data = request.get_json() ticket = Ticket( firstName=post_data.get('firstName'), lastName=post_data.get(""), notes=post_data.get("notes"), phone=post_data.get("phone"), email=post_data.get("email"), channel=post_data.get("channel"), lastModified=util.get_current_time(), modifiedBy=current_user.email_id, category=post_data.get("category"), status=post_data.get("status"), # createdOn = post_data.get(None, null=True), createdBy=current_user.email_id, isDeleted=False, projectId=projectId) ticket.create() res_payload = { 'id': ticket._id, 'firstName': ticket.firstName, 'lastName': ticket.lastName, 'channel': ticket.channel, 'createdOn': ticket.createdOn, 'status': ticket.status, 'notes': ticket.notes, 'category': ticket.category, 'phone': ticket.phone, 'email': ticket.email } return response_with_obj('success', 'Ticket created successfully', res_payload, 200) else: return response('failed', 'Content-type must be json', 402)
def search(current_user, workspaceId, projectId): """ Search Tickets """ query = request.json.get("query", "") filter_obj = request.json.get("filter", {}) pageNum = int(request.args.get('pageNum', 1)) itemsPerPage = int(request.args.get('itemsPerPage', 25)) print("Query and Filter:", query, filter_obj) tickets_list = Ticket.search_tickets(query, filter_obj, pageNum, itemsPerPage, projectId) totalItems = Ticket.get_total(projectId, query=query, filter_obj=filter_obj) displayName = { "id": "ID", "status": "Status", "category": "Category", "channel": "Channel", "name": "Name", "phone": "Phone", "email": "Email", "modifiedBy": "Modified By", "createdOn": "Created On", "lastModified": "Last Modified", } return { "tickets": tickets_list, "displayName": json.dumps(displayName), "pageNum": pageNum, "totalPages": math.ceil(totalItems / itemsPerPage), "totalEntries": totalItems }
def post(self): """ Creating an Ticket ad """ ticket_schema = TicketSchema() ticket_data = request.get_json() validated_ticket_data, errors = ticket_schema.load(ticket_data) if errors: return dict(status='fail', message=errors), 400 ticket = Ticket(**validated_ticket_data) saved_ticket = ticket.save() if not saved_ticket: return dict(status='fail', message='Internal Server Error'), 500 new_ticket_data, errors = ticket_schema.dumps(ticket) return dict(status='success', data=dict(ticket=json.loads(new_ticket_data))), 201
def add_ticket_to_db(ticket, date_search, iata_from_model, iata_to_model): ticket_info = check_ticket(ticket) if ticket_info["flights"][0]["invalid"] == 1: return ticket["price"] = ticket_info["flights_price"] new_ticket = Ticket( fly_from=iata_from_model, fly_to=iata_to_model, date_from=ticket["date_from"], date_to=ticket["date_to"], date_search=date_search, booking_token=ticket["booking_token"], price=ticket["price"], ) db_session.add(new_ticket) db_session.commit()
def get(self): """ Getting All tickets """ ticket_schema = TicketSchema(many=True) tickets = Ticket.find_all() tickets_data, errors = ticket_schema.dumps(tickets) if errors: return dict(status="fail", message="Internal Server Error"), 500 return dict(status="success", data=dict(tickets=json.loads(tickets_data))), 200
def create(self, db: Session, *, obj_in: TicketCreate) -> Ticket: db_obj = Ticket( ticket_id=obj_in.ticket_id, contract_nr=obj_in.contract_nr, customer_name=obj_in.customer_name, status=obj_in.status, kind=obj_in.kind, owner_id=obj_in.owner_id, store_internal_id=obj_in.store_internal_id, created_at=obj_in.created_at, updated_at=obj_in.updated_at, ) db.add(db_obj) db.commit() db.refresh(db_obj) return db_obj
def load_test_data(test_date): user = User('test123', 'abc123') user.save() user = User.query.all()[0] meal = Meal('Test meal', 'Meal desciption', test_date, b'009383615') meal.save() meal = Meal.query.all()[0] availability = Availability(test_date, meal.id) availability.save() availability = Availability.query.all()[0] ticket1 = Ticket(test_date, user.id, availability.id) ticket1.save() ticket2 = Ticket(test_date, user.id, availability.id) ticket2.save()
def get(self, request_args): """ Get user by id :param filter: Query string with filter[date] = timestamp of a date without hours """ if 'date' in request_args.filters: ticket_timestamp = TryParse.to_int(None, request_args.filters['date']) date_filter = TryParse.from_timestamp_to_datetime( None, ticket_timestamp) else: date_filter = datetime(2018, 3, 25) tickets = Ticket.find_by_date(date_filter) result = self.tickets_schema.dump(tickets) return jsonify_response(result.data, 200)
def delete(self, ticket_id): """ Delete a single ticket """ ticket = Ticket.get_by_id(ticket_id) if not ticket: return dict(status="fail", message=f"Ticket with id {ticket_id} not found"), 404 deleted_ticket = ticket.delete() if not deleted_ticket: return dict(status='fail', message='Internal Server Error'), 500 return dict(status='success', message="Successfully deleted"), 200
def get(self, ticket_id): """ Getting individual ticket """ schema = TicketSchema() ticket = Ticket.get_by_id(ticket_id) if not ticket: return dict(status="fail", message=f"Ticket with id {ticket_id} not found"), 404 ticket_data, errors = schema.dumps(ticket) if errors: return dict(status="fail", message=errors), 500 return dict(status='success', data=dict(ticket=json.loads(ticket_data))), 200
def api_list(self): self.context['data'] = Ticket.list_all()
def get(self, ticket_date): return Ticket.find_by_date(ticket_date), 200
class TicketService(): # def get_items(self, payment): # result = [0, 0, 0, 0, 0] # order_details = db.session.query(OrderDetails).filter_by(order_id=payment['order_id']).all() # for item in order_details: # data = item.as_dict() # result[data['ticket_id'] - 1] += data['count'] # return result # def count_ticket_left(self, payments): # reserved = [0, 0, 0, 0, 0] # paid = [0, 0, 0, 0, 0] # for payment in payments: # data = payment.as_dict() # if data['transaction_status'] is 'deny': # continue # count_data = self.get_items(data) # for i in range(0, 5): # if data['transaction_status'] == 'capture': # paid[i] += count_data[i] # else: # reserved[i] += count_data[i] # return {'reserved': reserved, 'paid': paid} # def include_ticket_left(self, tickets): # total_amount = [SLOT['commercial'], SLOT['commercial'], SLOT['commercial'], SLOT['commercial'], SLOT['community']] # payments = db.session.query(Payment).all() # data = self.count_ticket_left(payments) # for i in range(0, 5): # total_amount[i] -= data['reserved'][i] # total_amount[i] -= data['paid'][i] # return { # 'total_amount': total_amount, # 'reserved': data['reserved'], # 'paid': data['paid'] # } def get(self): tickets = db.session.query(Ticket).all() _results = [] for ticket in tickets: data = ticket.as_dict() if data['proposal_url'] is not None: data['proposal_url'] = Helper().url_helper( data['proposal_url'], current_app.config['GET_PROPOSAL_DOC_DEST']) _results.append(data) return { 'error': False, 'data': _results, 'message': 'Ticket retrieved succesfully' } # def include_count_data(self, count_data, results): # for i in range(0, 5): # results[i]['reserved'] = count_data['reserved'][i] # results[i]['paid'] = count_data['paid'][i] # results[i]['available'] = count_data['total_amount'][i] # return results def show(self, id): ticket = db.session.query(Ticket).filter_by(id=id).first() result = ticket.as_dict() if result['proposal_url']: result['proposal_url'] = Helper().url_helper( result['proposal_url'], current_app.config['GET_PROPOSAL_DOC_DEST']) return result def create(self, payloads): self.model_ticket = Ticket() self.model_ticket.ticket_type = payloads['ticket_type'] self.model_ticket.price = payloads['price'] self.model_ticket.information = payloads['information'] self.model_ticket.type = payloads['type'] self.model_ticket.usd_price = payloads['usd_price'] if payloads['type'] == TICKET_TYPES['exhibitor']: if payloads['proposal_url']: proposal_url = self.save_file( payloads['proposal_url'] ) if payloads['proposal_url'] is not None else None self.model_ticket.proposal_url = proposal_url db.session.add(self.model_ticket) try: db.session.commit() data = self.model_ticket.as_dict() if payloads['type'] == TICKET_TYPES['exhibitor'] and data[ 'proposal_url']: data['proposal_url'] = Helper().url_helper( data['proposal_url'], current_app.config['GET_PROPOSAL_DOC_DEST']) print(data['proposal_url']) return {'error': False, 'data': data} except SQLAlchemyError as e: data = e.orig.args return {'error': True, 'data': data} def update(self, payloads, id): try: self.model_ticket = db.session.query(Ticket).filter_by(id=id) proposal_url = self.save_file( payloads['proposal_url'] ) if payloads['proposal_url'] is not None else None self.model_ticket.update({ 'ticket_type': payloads['ticket_type'], 'price': payloads['price'], 'information': payloads['information'], 'type': payloads['type'], 'usd_price': payloads['usd_price'], 'quota': payloads['quota'], 'proposal_url': proposal_url, 'updated_at': datetime.datetime.now() }) db.session.commit() data = self.model_ticket.first().as_dict() return {'error': False, 'data': data} except SQLAlchemyError as e: data = e.orig.args return {'error': True, 'data': data} def delete(self, id): self.model_ticket = db.session.query(Ticket).filter_by(id=id) if self.model_ticket.first() is not None: # delete row self.model_ticket.delete() db.session.commit() return {'error': False, 'data': None} else: data = 'data not found' return {'error': True, 'data': data} def save_file(self, file, id=None): if file and Helper().allowed_file( file.filename, current_app.config['ALLOWED_PROPOSAL_DOC_EXTENSIONS']): filename = Helper().time_string() + "_" + file.filename.replace( " ", "_") file.save( os.path.join(current_app.config['POST_PROPOSAL_DOC_DEST'], filename)) return current_app.config['SAVE_PROPOSAL_DOC_DEST'] + filename else: return None
def api_seller_list(self, key=None): seller = self.util.decode_key(key).get() self.context['data'] = Ticket.list_per_user(seller.key)
def api_get_ticket(self, tckt_key=None): deal = self.util.decode_key(tckt_key).get() deals = Ticket.find_tickets(deal.key) self.context['data'] = deals
def save_tickets(tickets_data, event): """ Save all tickets :param tickets_data: :param event: :return: """ ticket_ids = [] for ticket_data in tickets_data: if ticket_data['id']: with db.session.no_autoflush: ticket = Ticket.query.filter_by(id=ticket_data['id'], event_id=event.id).first() ticket_tags=db.session.query(ticket_tags_table).filter_by(ticket_id=ticket.id) if ticket_tags.first(): ticket_tags.delete() else: ticket = Ticket(event=event) ticket.name = ticket_data['name'] ticket.quantity = ticket_data['quantity'] if ticket_data['quantity'] != '' else 100 ticket.type = ticket_data['type'] ticket.description_toggle = ticket_data['description_visibility'] ticket.description = ticket_data['description'] ticket.price = ticket_data['price'] if ticket_data['price'] != '' and ticket.type == 'paid' else 0 ticket.hide = ticket_data['ticket_visibility'] ticket.min_order = ticket_data['min_order'] if ticket_data['min_order'] != '' else 1 ticket.max_order = ticket_data['max_order'] if ticket_data['max_order'] != '' else 10 ticket.sales_start = get_event_time_field_format(ticket_data, 'sales_start') ticket.sales_end = get_event_time_field_format(ticket_data, 'sales_end') ticket.absorb_fees = ticket_data['absorb_fees'] if ticket_data['tags_string'].strip() != '': tag_names = ticket_data['tags_string'].split(',') for tag_name in tag_names: tag = TicketTag(name=tag_name, event_id=event.id) db.session.add(tag) db.session.add(ticket) ticket_ids.append(ticket.id) with db.session.no_autoflush: unwanted_tickets = Ticket.query.filter(~Ticket.id.in_(ticket_ids)).filter_by(event_id=event.id).all() for unwanted_ticket in unwanted_tickets: if not unwanted_ticket.has_order_tickets(): db.session.delete(unwanted_ticket)
def api_get_details(self, tckt_key=None): ticket = self.util.decode_key(tckt_key).get() # logging.info('===TICKETS == %s' % ticket) info = Ticket.to_message(ticket) self.context['data'] = info