Exemplo n.º 1
0
class AdminStatisticsGroupSchema(Schema):
    """
    Api schema
    """
    class Meta:
        """
        Meta class
        """

        type_ = 'admin-statistics-group'
        self_view = 'v1.admin_statistics_group_detail'
        inflect = dasherize

    id = fields.String()
    groups = fields.Method("number_of_groups")
    group_events = fields.Method("number_of_group_events")
    followers = fields.Method("number_of_followers")

    def number_of_groups(self, obj):
        all_group = db.session.query(Group).all()
        return len(all_group)

    def number_of_group_events(self, obj):
        unique_group = Event.query.filter(Event.group_id.isnot(None)).all()
        return len(unique_group)

    def number_of_followers(self, obj):
        unique_follower = db.session.query(UserFollowGroup.user_id).distinct()
        return unique_follower.count()
Exemplo n.º 2
0
class AdminSalesInvoicesSchema(Schema):
    """
    Sales invoices
    """

    class Meta:
        type_ = 'admin-sales-invoices'
        self_view = 'v1.admin_sales_invoices'
        inflect = dasherize

    id = fields.String()
    identifier = fields.String()
    status = fields.String()
    amount = fields.Float()
    created_at = fields.DateTime()
    completed_at = fields.DateTime()
    event_name = fields.Method('format_event_name')
    sent_to = fields.Method('format_sent_to')

    @staticmethod
    def format_event_name(self):
        return f'{self.event.name}'

    @staticmethod
    def format_sent_to(self):
        return f'{self.user.fullname} <{self.user.email}>'
class AdminStatisticsMailSchema(Schema):
    """
    Api schema
    """
    class Meta:
        """
        Meta class
        """
        type_ = 'admin-statistics-mail'
        self_view = 'v1.admin_statistics_mail_detail'
        inflect = dasherize

    id = fields.String()
    one_day = fields.Method("mail_last_1_day")
    three_days = fields.Method("mail_last_3_days")
    seven_days = fields.Method("mail_last_7_days")
    thirty_days = fields.Method("mail_last_30_days")

    def mail_last_1_day(self, obj):
        return get_count(Mail.query.filter(datetime.now(pytz.utc) - Mail.time <= timedelta(days=1)))

    def mail_last_3_days(self, obj):
        return get_count(Mail.query.filter(datetime.now(pytz.utc) - Mail.time <= timedelta(days=3)))

    def mail_last_7_days(self, obj):
        return get_count(Mail.query.filter(datetime.now(pytz.utc) - Mail.time <= timedelta(days=7)))

    def mail_last_30_days(self, obj):
        return get_count(Mail.query.filter(datetime.now(pytz.utc) - Mail.time <= timedelta(days=30)))
Exemplo n.º 4
0
class AdminSalesFeesSchema(Schema):
    """
    Sales fees and revenue for all events
    """
    class Meta:
        type_ = 'admin-sales-fees'
        self_view = 'v1.admin_sales_fees'
        inflect = dasherize

    id = fields.String()
    name = fields.String()
    payment_currency = fields.String()
    fee_percentage = fields.Float(attribute='fee')
    maximum_fee = fields.Float(attribute='maximum_fee')
    revenue = fields.Method('calc_revenue')
    ticket_count = fields.Method('calc_ticket_count')
    event_date = fields.Method('get_event_date')

    @staticmethod
    def calc_ticket_count(obj):
        """Count all tickets in all orders of this event"""
        return sum(
            [o.tickets_count for o in obj.orders if o.status == 'completed'])

    @staticmethod
    def calc_revenue(obj):
        """Returns total revenues of all completed orders for the given event"""
        return sum(
            [o.get_revenue() for o in obj.orders if o.status == 'completed'])

    @staticmethod
    def get_event_date(obj):
        return obj.starts_at.isoformat()
Exemplo n.º 5
0
class AdminStatisticsEventSchema(Schema):
    """
    Api schema
    """

    class Meta:
        """
        Meta class
        """

        type_ = 'admin-statistics-event'
        self_view = 'v1.admin_statistics_event_detail'
        inflect = dasherize

    id = fields.String()
    draft = fields.Method("events_draft_count")
    published = fields.Method("events_published_count")
    past = fields.Method("events_past_count")

    def events_draft_count(self, obj):
        events = Event.query.filter(Event.ends_at > datetime.now(pytz.utc))
        return get_count(events.filter_by(state='draft', deleted_at=None))

    def events_published_count(self, obj):
        events = Event.query.filter(Event.ends_at > datetime.now(pytz.utc))
        return get_count(events.filter_by(state='published', deleted_at=None))

    def events_past_count(self, obj):
        return get_count(Event.query.filter(Event.ends_at < datetime.now(pytz.utc)))
Exemplo n.º 6
0
class AdminSalesByEventsSchema(Schema):
    """
    Sales summarized by event

    Provides
        event(name),
        date,
        count of tickets and total sales for orders grouped by status
    """

    class Meta:
        type_ = 'admin-sales-by-events'
        self_view = 'v1.admin_sales_by_events'
        inflect = dasherize

    id = fields.String()
    identifier = fields.String()
    name = fields.String()
    created_at = fields.DateTime()
    deleted_at = fields.DateTime()
    starts_at = fields.DateTime()
    ends_at = fields.DateTime()
    payment_currency = fields.String()
    payment_country = fields.String()
    completed_order_sales = fields.Integer(dump_only=True)
    placed_order_sales = fields.Integer(dump_only=True)
    pending_order_sales = fields.Integer(dump_only=True)
    completed_order_tickets = fields.Integer(dump_only=True)
    placed_order_tickets = fields.Integer(dump_only=True)
    pending_order_tickets = fields.Integer(dump_only=True)
    type = fields.Method('event_type')
    owner = fields.Method('event_owner')
    owner_id = fields.Method('event_owner_id')

    def event_owner(self, obj):
        return str(obj.owner.email)

    def event_owner_id(self, obj):
        return obj.owner.id

    def event_type(self, obj):
        t = 'To be announced'
        if obj.online:
            if obj.location_name:
                t = 'Hybrid'
            else:
                t = 'Online'
        elif obj.location_name:
            t = 'Venue'
        return str(t)
Exemplo n.º 7
0
class AdminStatisticsUserSchema(Schema):
    """
    Api schema
    """
    class Meta:
        """
        Meta class
        """
        type_ = 'admin-statistics-user'
        self_view = 'v1.admin_statistics_user_detail'
        inflect = dasherize

    id = fields.String()
    super_admin = fields.Method("super_admin_count")
    admin = fields.Method("admin_count")
    verified = fields.Method("verified_count")
    unverified = fields.Method("unverified_count")
    organizer = fields.Method("organizer_count")
    coorganizer = fields.Method("coorganizer_count")
    attendee = fields.Method("attendee_count")
    track_organizer = fields.Method("track_organizer_count")

    def super_admin_count(self, obj):
        return get_count(User.query.filter_by(is_super_admin=True))

    def admin_count(self, obj):
        return get_count(
            User.query.filter_by(is_admin=True, is_super_admin=False))

    def verified_count(self, obj):
        return get_count(
            User.query.filter_by(is_verified=True,
                                 is_super_admin=False,
                                 is_admin=False))

    def unverified_count(self, obj):
        return get_count(
            User.query.filter_by(is_verified=False,
                                 is_super_admin=False,
                                 is_admin=False))

    def get_all_user_roles(self, role_name):
        role = Role.query.filter_by(name=role_name).first()
        newquery = User.query.join(UsersEventsRoles.user).join(
            UsersEventsRoles.role).filter(
                UsersEventsRoles.role == role).distinct()
        return newquery

    def organizer_count(self, obj):
        return self.get_all_user_roles('organizer').count()

    def coorganizer_count(self, obj):
        return self.get_all_user_roles('coorganizer').count()

    def track_organizer_count(self, obj):
        return self.get_all_user_roles('track_organizer').count()

    def attendee_count(self, obj):
        unique_attendee_query = db.session.query(TicketHolder.email).distinct()
        return unique_attendee_query.count()
Exemplo n.º 8
0
class AdminStatisticsUserSchema(Schema):
    """
    Api schema
    """
    class Meta:
        """
        Meta class
        """
        type_ = 'admin-statistics-user'
        self_view = 'v1.admin_statistics_user_detail'
        inflect = dasherize

    id = fields.String()
    super_admin = fields.Method("super_admin_count")
    admin = fields.Method("admin_count")
    verified = fields.Method("verified_count")
    unverified = fields.Method("unverified_count")
    organizer = fields.Method("organizer_count")
    coorganizer = fields.Method("coorganizer_count")
    attendee = fields.Method("attendee_count")
    track_organizer = fields.Method("track_organizer_count")

    def super_admin_count(self, obj):
        return get_count(User.query.filter_by(is_super_admin=True))

    def admin_count(self, obj):
        return get_count(
            User.query.filter_by(is_admin=True, is_super_admin=False))

    def verified_count(self, obj):
        return get_count(
            User.query.filter_by(is_verified=True,
                                 is_super_admin=False,
                                 is_admin=False))

    def unverified_count(self, obj):
        return get_count(
            User.query.filter_by(is_verified=False,
                                 is_super_admin=False,
                                 is_admin=False))

    def get_all_user_roles(self, role_name):
        role = Role.query.filter_by(name=role_name).first()
        uers = UsersEventsRoles.query.join(UsersEventsRoles.event).join(
            UsersEventsRoles.role).filter(Event.deleted_at.is_(None),
                                          UsersEventsRoles.role == role)
        return uers

    def organizer_count(self, obj):
        return get_count(self.get_all_user_roles('organizer'))

    def coorganizer_count(self, obj):
        return get_count(self.get_all_user_roles('coorganizer'))

    def track_organizer_count(self, obj):
        return get_count(self.get_all_user_roles('track_organizer'))

    def attendee_count(self, obj):
        return get_count(self.get_all_user_roles('attendee'))
Exemplo n.º 9
0
class AdvertSchema(Schema):
    id = fields.Integer(dump_only=True)
    title = fields.String()
    images_set = fields.Relationship(schema=ImageSchema,
                                     many=True,
                                     dump_only=True,
                                     dump_to='images')
    description = fields.String()
    author = fields.Relationship(
        schema=UserSchema,
        type_='user',
        related_url='/api/v1/users/{author_id}',
        related_url_kwargs={'author_id': '<author.id>'},
        include_resource_linkage=False)
    # timestamp = TimeStampConvertedField()
    price = fields.Float()
    timestamp = fields.LocalDateTime('%Y%m%d%H%M%S', dump_only=True)
    key = fields.Method('ExampleKeyGenerated', dump_only=True)

    class Meta:
        type_ = 'advert'
        additional = ('id', )

    def ExampleKeyGenerated(self, obj):
        return ''.join(('@', str(obj.item)))

    @post_load
    def make_advert(self, data):
        return Adverts(**data)
Exemplo n.º 10
0
class AdminSalesByLocationSchema(Schema):
    """
    Sales summarized by location

    Provides
        location name,
        count of tickets and total sales for orders grouped by status
    """

    class Meta:
        type_ = 'admin-sales-by-location'
        self_view = 'v1.admin_sales_by_location'
        inflect = dasherize

    id = fields.String()
    location_name = fields.String()
    sales = fields.Method('calc_sales')

    @staticmethod
    def calc_sales(obj):
        """
        Returns sales (dictionary with total sales and ticket count) for
        placed, completed and pending orders
        """
        res = {'placed': {}, 'completed': {}, 'pending': {}}
        res['placed']['sales_total'] = obj.placed_sales or 0
        res['placed']['ticket_count'] = obj.placed_tickets or 0
        res['completed']['sales_total'] = obj.completed_sales or 0
        res['completed']['ticket_count'] = obj.completed_tickets or 0
        res['pending']['sales_total'] = obj.pending_sales or 0
        res['pending']['ticket_count'] = obj.pending_tickets or 0

        return res
Exemplo n.º 11
0
class AdminSalesByEventsSchema(Schema):
    """
    Sales summarized by event

    Provides
        event(name),
        date,
        count of tickets and total sales for orders grouped by status
    """
    class Meta:
        type_ = 'admin-sales-by-events'
        self_view = 'v1.admin_sales_by_events'
        inflect = dasherize

    id = fields.String()
    identifier = fields.String()
    name = fields.String()
    created_at = fields.DateTime()
    deleted_at = fields.DateTime()
    starts_at = fields.DateTime()
    ends_at = fields.DateTime()
    payment_currency = fields.String()
    payment_country = fields.String()
    sales = fields.Method('calc_sales')

    @staticmethod
    def calc_sales(obj):
        """
        Returns sales (dictionary with total sales and ticket count) for
        placed, completed and pending orders
        """
        return summary(obj)
class AdminSalesByMarketerSchema(Schema):
    """
    Sales summarized by marketer

    Provides
        marketer name,
        count of tickets and total sales for orders grouped by status
    """

    class Meta:
        type_ = 'admin-sales-by-marketer'
        self_view = 'v1.admin_sales_by_marketer'

    id = fields.String()
    fullname = fields.String()
    email = fields.String()
    sales = fields.Method('calc_sales')

    @staticmethod
    def calc_sales(obj):
        """
        Returns sales (dictionary with total sales and ticket count) for
        placed, completed and pending orders
        """
        return summary(obj.orders)
Exemplo n.º 13
0
class AdminSalesByOrganizersSchema(Schema):
    """
    Sales summarized by organizer

    Provides
        organizer (first name, last name and email),
        count of tickets and total sales for orders grouped by status
    """
    class Meta:
        type_ = 'admin-sales-by-organizers'
        self_view = 'v1.admin_sales_by_organizers'
        inflect = dasherize

    id = fields.String()
    first_name = fields.String()
    last_name = fields.String()
    email = fields.String()
    starts_at = fields.DateTime()
    ends_at = fields.DateTime()
    sales = fields.Method('calc_sales')

    @staticmethod
    def calc_sales(obj):
        """
        Returns sales (dictionary with total sales and ticket count) for
        placed, completed and pending orders
        """
        return summary(obj.orders)
class EventStatisticsGeneralSchema(Schema):
    """
    Api schema for general statistics of event
    """
    class Meta:
        """
        Meta class
        """
        type_ = 'event-statistics-general'
        self_view = 'v1.event_statistics_general_detail'
        self_view_kwargs = {'id': '<id>'}
        inflect = dasherize

    id = fields.Str()
    identifier = fields.Str()
    sessions_draft = fields.Method("sessions_draft_count")
    sessions_submitted = fields.Method("sessions_submitted_count")
    sessions_accepted = fields.Method("sessions_accepted_count")
    sessions_confirmed = fields.Method("sessions_confirmed_count")
    sessions_pending = fields.Method("sessions_pending_count")
    sessions_rejected = fields.Method("sessions_rejected_count")
    speakers = fields.Method("speakers_count")
    sessions = fields.Method("sessions_count")
    sponsors = fields.Method("sponsors_count")

    def sessions_draft_count(self, obj):
        return Session.query.filter_by(event_id=obj.id, state='draft').count()

    def sessions_submitted_count(self, obj):
        return Session.query.filter_by(event_id=obj.id, state='submitted').count()

    def sessions_accepted_count(self, obj):
        return Session.query.filter_by(event_id=obj.id, state='accepted').count()

    def sessions_confirmed_count(self, obj):
        return Session.query.filter_by(event_id=obj.id, state='confirmed').count()

    def sessions_pending_count(self, obj):
        return Session.query.filter_by(event_id=obj.id, state='pending').count()

    def sessions_rejected_count(self, obj):
        return Session.query.filter_by(event_id=obj.id, state='rejected').count()

    def speakers_count(self, obj):
        return Speaker.query.filter_by(event_id=obj.id).count()

    def sessions_count(self, obj):
        return Session.query.filter_by(event_id=obj.id).count()

    def sponsors_count(self, obj):
        return Sponsor.query.filter_by(event_id=obj.id).count()
Exemplo n.º 15
0
        class ContextTestSchema(Schema):
            id = fields.Str()
            from_context = fields.Method("get_from_context")

            def get_from_context(self, obj):
                return self.context["some_value"]

            class Meta:
                type_ = "people"
Exemplo n.º 16
0
        class ContextTestSchema(Schema):
            id = fields.Str()
            from_context = fields.Method('get_from_context')

            def get_from_context(self, obj):
                return self.context['some_value']

            class Meta:
                type_ = 'people'
Exemplo n.º 17
0
class EventOrgaSchema(Schema):
    """
    Schema for Orga Events - a minified version of Events for the Organizer App
    """
    class Meta:
        type_ = 'event-orga'
        self_view = 'v1.events_orga'
        self_view_kwargs = {'id': '<id>'}
        inflect = dasherize

    id = fields.Str(dump_only=True)
    name = fields.Str(required=True)
    starts_at = fields.DateTime(required=True, timezone=True)
    tickets_available = fields.Method('calc_total_tickets_count')
    tickets_sold = fields.Method('calc_tickets_sold_count')
    revenue = fields.Method('calc_revenue')
    payment_currency = fields.Str(allow_none=True)

    @staticmethod
    def calc_tickets_sold_count(obj):
        """Calculate total number of tickets sold for the event"""
        return db.session.query(Order.event_id).filter_by(event_id=obj.id, status='completed').join(TicketHolder)\
            .count()

    @staticmethod
    def calc_total_tickets_count(obj):
        """Calculate total available tickets for all types of tickets"""
        total_available = db.session.query(func.sum(
            Ticket.quantity)).filter_by(event_id=obj.id).scalar()
        if total_available is None:
            total_available = 0
        return total_available

    @staticmethod
    def calc_revenue(obj):
        """Returns total revenues of all completed orders for the given event"""
        revenue = db.session.query(func.sum(Order.amount)).filter_by(
            event_id=obj.id, status='completed').scalar()
        if revenue is None:
            revenue = 0
        return revenue
Exemplo n.º 18
0
class BundleDependencySchema(PlainSchema):
    """
    Plain (non-JSONAPI) Marshmallow schema for a single bundle dependency.
    Not defining this as a separate resource with Relationships because we only
    create a set of dependencies once at bundle creation.
    """
    child_uuid = fields.String(validate=validate_uuid, dump_only=True)
    child_path = fields.String()  # Validated in Bundle ORMObject
    parent_uuid = fields.String(validate=validate_uuid)
    parent_path = fields.String(missing="")
    parent_name = fields.Method('get_parent_name', dump_only=True)  # for convenience

    def get_parent_name(self, dep):
        uuid = dep['parent_uuid']
        return local.model.get_bundle_names([uuid]).get(uuid)
Exemplo n.º 19
0
class AdminSalesDiscountedSchema(Schema):
    """
    Discounted sales by event

    Provides
        Event name,
        discount code,
        marketer mail,
        count of tickets and total sales for orders grouped by status
    """

    class Meta:
        type_ = 'admin-sales-discounted'
        self_view = 'v1.admin_sales_discounted'
        inflect = dasherize

    id = fields.String()
    code = fields.String()
    email = fields.String()
    event_name = fields.String()
    payment_currency = fields.String()
    sales = fields.Method('calc_sales')

    @staticmethod
    def calc_sales(obj):
        """
        Returns sales (dictionary with total sales and ticket count) for
        placed, completed and pending orders
        """
        res = {'placed': {}, 'completed': {}, 'pending': {}}
        res['placed']['sales_total'] = obj.placed_sales or 0
        res['placed']['ticket_count'] = obj.placed_tickets or 0
        res['completed']['sales_total'] = obj.completed_sales or 0
        res['completed']['ticket_count'] = obj.completed_tickets or 0
        res['pending']['sales_total'] = obj.pending_sales or 0
        res['pending']['ticket_count'] = obj.pending_tickets or 0

        return res
Exemplo n.º 20
0
class AdminStatisticsSessionSchema(Schema):
    """
    Api schema
    """
    class Meta:
        """
        Meta class
        """

        type_ = 'admin-statistics-session'
        self_view = 'v1.admin_statistics_session_detail'
        inflect = dasherize

    id = fields.String()
    draft = fields.Method("sessions_draft_count")
    submitted = fields.Method("sessions_submitted_count")
    accepted = fields.Method("sessions_accepted_count")
    confirmed = fields.Method("sessions_confirmed_count")
    pending = fields.Method("sessions_pending_count")
    rejected = fields.Method("sessions_rejected_count")

    def sessions_draft_count(self, obj):
        return get_count(Session.query.filter_by(state='draft'))

    def sessions_submitted_count(self, obj):
        return get_count(Session.query.filter_by(state='submitted'))

    def sessions_accepted_count(self, obj):
        return get_count(Session.query.filter_by(state='accepted'))

    def sessions_confirmed_count(self, obj):
        return get_count(Session.query.filter_by(state='confirmed'))

    def sessions_pending_count(self, obj):
        return get_count(Session.query.filter_by(state='pending'))

    def sessions_rejected_count(self, obj):
        return get_count(Session.query.filter_by(state='rejected'))
Exemplo n.º 21
0
class ProcessStatisticsSchema(Schema):
    """
    Api schema
    """
    class Meta:
        """
        Meta class
        """
        type_ = 'process-statistics'
        self_view = 'v1.process_statistics_detail'
        inflect = dasherize

    id = fields.String()
    total_requests = fields.Method("total_requests")
    active_get_requests = fields.Method("active_get_requests")
    active_post_requests = fields.Method("active_post_requests")
    active_put_requests = fields.Method("active_put_requests")
    total_requests_past_hour = fields.Method("total_requests_past_hour")
    total_requests_past_minute = fields.Method("total_requests_past_minute")
    avg_response_time_past_minute = fields.Method(
        "avg_response_time_past_minute")
    avg_response_time_past_hour = fields.Method("avg_response_time_past_hour")

    def total_requests(self, obj):
        return get_count(Process.query.all())

    def active_get_requests(self, obj):
        return get_count(Process.query.filter_by(method="GET"))

    def active_post_requests(self, obj):
        return get_count(Process.query.filter_by(method="POST"))

    def active_put_requests(self, obj):
        return get_count(Process.query.filter_by(method="PUT"))

    def total_requests_past_hour(self, obj):
        all_processes = get_count(
            Process.query.filter_by(time=datetime.now(pytz.utc)))
        processes_till_last_1_hour = get_count(
            Process.query.filter(
                Process.time <= datetime.now(pytz.utc) - timedelta(hours=1)))
        return all_processes - processes_till_last_1_hour

    def total_requests_past_minute(self, obj):
        all_processes = get_count(
            Process.query.filter_by(time=datetime.now(pytz.utc)))
        processes_till_last_1_min = get_count(
            Process.query.filter(
                Process.time <= datetime.now(pytz.utc) - timedelta(minutes=1)))
        return all_processes - processes_till_last_1_min

    def avg_response_time_past_minute(self, obj):
        requests = self.total_requests_past_minute()
        total_time = 0
        for process in Process.query.order_by(
                Process.id.desc()).limit(requests):
            total_time += process.duration
        return total_time // requests

    def avg_response_time_past_hour(self, obj):
        requests = self.total_requests_past_hour()
        total_time = 0
        for process in Process.query.order_by(
                Process.id.desc()).limit(requests):
            total_time += process.duration
        return total_time // requests
Exemplo n.º 22
0
class EventStatisticsGeneralSchema(Schema):
    """
    Api schema for general statistics of event
    """
    class Meta:
        """
        Meta class
        """
        type_ = 'event-statistics-general'
        self_view = 'v1.event_statistics_general_detail'
        self_view_kwargs = {'id': '<id>'}
        inflect = dasherize

    id = fields.Str()
    identifier = fields.Str()
    sessions_draft = fields.Method("sessions_draft_count")
    sessions_submitted = fields.Method("sessions_submitted_count")
    sessions_accepted = fields.Method("sessions_accepted_count")
    sessions_confirmed = fields.Method("sessions_confirmed_count")
    sessions_pending = fields.Method("sessions_pending_count")
    sessions_rejected = fields.Method("sessions_rejected_count")
    speakers = fields.Method("speakers_count")
    sessions = fields.Method("sessions_count")
    sponsors = fields.Method("sponsors_count")

    def sessions_draft_count(self, obj):
        return Session.query.filter_by(event_id=obj.id, state='draft', deleted_at=None).count()

    def sessions_submitted_count(self, obj):
        return Session.query.filter_by(event_id=obj.id, deleted_at=None).count()

    def sessions_accepted_count(self, obj):
        return Session.query.filter_by(event_id=obj.id, state='accepted', deleted_at=None).count()

    def sessions_confirmed_count(self, obj):
        return Session.query.filter_by(event_id=obj.id, state='confirmed', deleted_at=None).count()

    def sessions_pending_count(self, obj):
        return Session.query.filter_by(event_id=obj.id, state='pending', deleted_at=None).count()

    def sessions_rejected_count(self, obj):
        return Session.query.filter_by(event_id=obj.id, state='rejected', deleted_at=None).count()

    def speakers_count_type(self, obj, state='pending'):
        return SessionsSpeakersLink.query.filter_by(event_id=obj.id, session_state=state, deleted_at=None).count()

    def speakers_count(self, obj):
        accepted = self.speakers_count_type(obj=obj, state='accepted')
        confirmed = self.speakers_count_type(obj=obj, state='confirmed')
        pending = self.speakers_count_type(obj=obj, state='pending')
        rejected = self.speakers_count_type(obj=obj, state='rejected')
        total = Speaker.query.filter_by(event_id=obj.id, deleted_at=None).count()
        serial_data = {
                       'accepted': accepted,
                       'confirmed': confirmed,
                       'pending': pending,
                       'rejected': rejected,
                       'total': total
                       }
        return serial_data

    def sessions_count(self, obj):
        return Session.query.filter_by(event_id=obj.id, deleted_at=None).count()

    def sponsors_count(self, obj):
        return Sponsor.query.filter_by(event_id=obj.id, deleted_at=None).count()
Exemplo n.º 23
0
class EventStatisticsGeneralSchema(Schema):
    """
    Api schema for general statistics of event
    """
    class Meta:
        """
        Meta class
        """

        type_ = 'event-statistics-general'
        self_view = 'v1.event_statistics_general_detail'
        self_view_kwargs = {'id': '<id>'}
        inflect = dasherize

    id = fields.Str()
    identifier = fields.Str()
    sessions_draft = fields.Method("sessions_draft_count")
    sessions_submitted = fields.Method("sessions_submitted_count")
    sessions_accepted = fields.Method("sessions_accepted_count")
    sessions_confirmed = fields.Method("sessions_confirmed_count")
    sessions_pending = fields.Method("sessions_pending_count")
    sessions_rejected = fields.Method("sessions_rejected_count")
    sessions_withdrawn = fields.Method("sessions_withdrawn_count")
    sessions_canceled = fields.Method("sessions_canceled_count")
    speakers = fields.Method("speakers_count")
    sessions = fields.Method("sessions_count")
    sponsors = fields.Method("sponsors_count")
    speaker_without_session = fields.Method("speaker_without_session_count")

    @cache.memoize(50)
    def get_session_stats(self, event):
        stats = (Session.query.filter_by(
            event_id=event.id, deleted_at=None).with_entities(
                Session.state, func.count()).group_by(Session.state).all())
        data = dict(stats)
        data['all'] = sum([x for _, x in stats])

        return data

    def sessions_draft_count(self, obj):
        return self.get_session_stats(obj).get('draft', 0)

    def sessions_submitted_count(self, obj):
        return self.get_session_stats(obj).get('all', 0)

    def sessions_accepted_count(self, obj):
        return self.get_session_stats(obj).get('accepted', 0)

    def sessions_confirmed_count(self, obj):
        return self.get_session_stats(obj).get('confirmed', 0)

    def sessions_pending_count(self, obj):
        return self.get_session_stats(obj).get('pending', 0)

    def sessions_rejected_count(self, obj):
        return self.get_session_stats(obj).get('rejected', 0)

    def sessions_withdrawn_count(self, obj):
        return self.get_session_stats(obj).get('withdrawn', 0)

    def sessions_canceled_count(self, obj):
        return self.get_session_stats(obj).get('canceled', 0)

    def get_speaker_stats(self, event):
        stats = (Speaker.query.join(Speaker.sessions).filter(
            Speaker.event_id == event.id,
            Speaker.deleted_at == None,
            Session.deleted_at == None,
        ).with_entities(Session.state, func.count(distinct(
            Speaker.id))).group_by(Session.state).all())
        data = dict(stats)
        data['total'] = sum([x for _, x in stats])

        return data

    def speaker_without_session_count(self, obj):
        return Speaker.query.filter(
            Speaker.sessions == None,
            Speaker.event_id == obj.id,
            Speaker.deleted_at == None,
        ).count()

    @cache.memoize(50)
    def speakers_count(self, obj):
        stats = self.get_speaker_stats(obj)
        serial_data = {
            'accepted': 0,
            'confirmed': 0,
            'pending': 0,
            'rejected': 0,
            'withdrawn': 0,
            'canceled': 0,
            'total': 0,
            **stats,
        }
        return serial_data

    @cache.memoize(50)
    def sessions_count(self, obj):
        return Session.query.filter_by(event_id=obj.id,
                                       deleted_at=None).count()

    @cache.memoize(50)
    def sponsors_count(self, obj):
        return Sponsor.query.filter_by(event_id=obj.id,
                                       deleted_at=None).count()
class OrderStatisticsEventSchema(Schema):
    """
    Api schema for general statistics of event
    """

    class Meta:
        """
        Meta class
        """
        type_ = 'order-statistics-event'
        self_view = 'v1.order_statistics_event_detail'
        self_view_kwargs = {'id': '<id>'}
        inflect = dasherize

    id = fields.Str()
    identifier = fields.Str()
    tickets = fields.Method("tickets_count")
    orders = fields.Method("orders_count")
    sales = fields.Method("sales_count")

    def tickets_count(self, obj):
        obj_id = obj.id
        total = db.session.query(func.sum(OrderTicket.quantity.label('sum'))).join(Order.order_tickets).filter(
            Order.event_id == obj_id).scalar()
        draft = db.session.query(func.sum(OrderTicket.quantity.label('sum'))).join(Order.order_tickets).filter(
            Order.event_id == obj_id, Order.status == 'draft').scalar()
        cancelled = db.session.query(func.sum(OrderTicket.quantity.label('sum'))).join(Order.order_tickets).filter(
            Order.event_id == obj_id, Order.status == 'cancelled').scalar()
        pending = db.session.query(func.sum(OrderTicket.quantity.label('sum'))).join(Order.order_tickets).filter(
            Order.event_id == obj_id, Order.status == 'pending').scalar()
        expired = db.session.query(func.sum(OrderTicket.quantity.label('sum'))).join(Order.order_tickets).filter(
            Order.event_id == obj_id, Order.status == 'expired').scalar()
        placed = db.session.query(func.sum(OrderTicket.quantity.label('sum'))).join(Order.order_tickets).filter(
            Order.event_id == obj_id, Order.status == 'placed').scalar()
        result = {
            'total': total or 0,
            'draft': draft or 0,
            'cancelled': cancelled or 0,
            'pending': pending or 0,
            'expired': expired or 0,
            'placed': placed or 0
        }
        return result

    def orders_count(self, obj):
        obj_id = obj.id
        total = get_count(db.session.query(Order).filter(Order.event_id == obj_id))
        draft = get_count(db.session.query(Order).filter(Order.event_id == obj_id, Order.status == 'draft'))
        cancelled = get_count(db.session.query(Order).filter(Order.event_id == obj_id, Order.status == 'cancelled'))
        pending = get_count(db.session.query(Order).filter(Order.event_id == obj_id, Order.status == 'pending'))
        expired = get_count(db.session.query(Order).filter(Order.event_id == obj_id, Order.status == 'expired'))
        placed = get_count(db.session.query(Order).filter(Order.event_id == obj_id, Order.status == 'placed'))
        result = {
            'total': total or 0,
            'draft': draft or 0,
            'cancelled': cancelled or 0,
            'pending': pending or 0,
            'expired': expired or 0,
            'placed': placed or 0
        }
        return result

    def sales_count(self, obj):
        obj_id = obj.id
        total = db.session.query(func.sum(Order.amount.label('sum'))).filter(Order.event_id == obj_id).scalar()
        draft = db.session.query(func.sum(Order.amount.label('sum'))).filter(Order.event_id == obj_id,
                                                                             Order.status == 'draft').scalar()
        cancelled = db.session.query(func.sum(Order.amount.label('sum'))).filter(Order.event_id == obj_id,
                                                                                 Order.status == 'cancelled').scalar()
        pending = db.session.query(func.sum(Order.amount.label('sum'))).filter(Order.event_id == obj_id,
                                                                               Order.status == 'pending').scalar()
        expired = db.session.query(func.sum(Order.amount.label('sum'))).filter(Order.event_id == obj_id,
                                                                               Order.status == 'expired').scalar()
        placed = db.session.query(func.sum(Order.amount.label('sum'))).filter(Order.event_id == obj_id,
                                                                              Order.status == 'placed').scalar()
        result = {
            'total': total or 0,
            'draft': draft or 0,
            'cancelled': cancelled or 0,
            'pending': pending or 0,
            'expired': expired or 0,
            'placed': placed or 0
        }
        return result