Esempio n. 1
0
    def check_membership(self, party_id):
        profile = ProfileService().get(id=self.request.user.id)
        party = PartyService().get(id=party_id)

        if not MemberService().is_party_member(profile, party):
            raise PermissionDenied("You are not a member of this party")
        return True
Esempio n. 2
0
    def post(self, request):
        create_party_form = CreatePartyForm(request.POST, user=request.user)
        members_form = PartyMemberFormSet(request.POST, user=request.user)

        if not create_party_form.is_valid():
            errors = get_form_errors_as_str(create_party_form)
            messages.error(request, errors)
            return redirect(reverse(HomeView.name))
        elif not members_form.is_valid():
            errors = get_formset_errors_as_str(members_form)
            messages.error(request, errors)
            return redirect(reverse(HomeView.name))
        else:
            name = create_party_form.cleaned_data.get('name')
            creator = ProfileService().get(id=request.user.id)
            members = []
            for form in members_form:
                profile = form.cleaned_data.get('profile')
                if profile:
                    members.append(profile)

            party = PartyService().create(name=name,
                                          creator=creator,
                                          members=members)

        return redirect(reverse(PartyView.name, kwargs={'party_id': party.id}))
Esempio n. 3
0
    def post(self, request, party_id: int, **kwargs):
        order_item_id = int(request.POST.get('order_item'))
        user_id = request.user.id

        profile = ProfileService().get(id=user_id)
        order_item = OrderService().get(id=order_item_id)
        MemberService().member_include_food(profile, order_item)

        return redirect(reverse(PartyView.name, kwargs={'party_id': party_id}))
Esempio n. 4
0
    def save(self, commit=True) -> Party:
        name = self.cleaned_data.get('name')
        members = self.cleaned_data.get('members')

        creator = ProfileService().get(id=self.user.id)
        party = PartyService().create(name=name,
                                      creator=creator,
                                      members=members)

        return party
Esempio n. 5
0
    def save(self, commit=True) -> TemplateParty:
        name = self.cleaned_data.get('name')
        members = self.cleaned_data.get('members')
        food = self.cleaned_data.get('food')

        creator = ProfileService().get(id=self.user.id)
        return TemplatePartyService().create(name=name,
                                             creator=creator,
                                             members=members,
                                             food=food)
Esempio n. 6
0
    def get_context_data(self, **kwargs):
        context = {}
        profile_service = ProfileService()

        if self.request.user.is_authenticated:
            profile = profile_service.get(id=self.request.user.id)
            context['parties'] = profile_service.get_profile_parties(profile)
            context[
                'adm_parties'] = profile_service.get_profile_administrated_parties(
                    profile)

            context[CreatePartyForm.form_name] = CreatePartyForm(
                user=self.request.user)
            context[CreatePartyFromExistingForm.
                    form_name] = CreatePartyFromExistingForm(
                        user=self.request.user)

            context['formset'] = PartyMemberFormSet()

        return context
Esempio n. 7
0
    def save(self, commit=True):
        name = self.cleaned_data.get('name')
        existing_party_name = self.cleaned_data.get('existing_party_name')

        ps = PartyService()
        existing_party = ps.get(name=existing_party_name)
        creator = ProfileService().get(id=self.user.id)
        members = ps.get_party_profiles(existing_party,
                                        excluding={'id': creator.id})

        return ps.create(name=name, creator=creator, members=members)
Esempio n. 8
0
    def get(self, request, verification_code):
        message = "Your profile has been successfully activated."

        from django.core.exceptions import ValidationError
        try:
            verified = ProfileService().activate_profile(verification_code)
            if not verified:
                message = "It seems your profile has been already activated"
        except (Code.DoesNotExist, ValidationError):
            message = 'Such verification code does not exist'

        return HttpResponse(message)
Esempio n. 9
0
    def post(self, request, party_id: int, **kwargs):
        profile = ProfileService().get(id=request.user.id)
        party = PartyService().get(id=party_id)
        member = MemberService().get(party=party, profile=profile)

        form = SponsorPartyForm(request.POST, member=member)
        if not form.is_valid():
            errors = get_form_errors_as_str(form)
            messages.error(request, errors)
        else:
            amount = form.cleaned_data.get('amount')
            PartyService().sponsor_party(member, amount)

        return redirect(reverse(PartyView.name, kwargs={'party_id': party_id}))
Esempio n. 10
0
class CreatePartyTestCase(TestCase):
    party_service = PartyService()
    profile_service = ProfileService()

    def setUp(self):
        Profile.objects.create(username='******')
        Profile.objects.create(username='******')

    def test_create_party(self):
        creator = Profile.objects.get(username='******')

        party_to_create = self.party_service.create(name='test_party',
                                                    creator=creator)

        actual_party = Party.objects.get(name='test_party')

        self.assertEqual(party_to_create, actual_party)
Esempio n. 11
0
class RemoveMemberFromPartyTestCase(TestCase):
    party_service = PartyService()
    profile_service = ProfileService()

    def setUp(self):
        creator = Profile.objects.create(username='******')
        member = Profile.objects.create(username='******')

        party = Party.objects.create(name='test_party', created_by=creator)
        Membership.objects.create(party=party, profile=member)

    def test_remove_member(self):
        party = self.party_service.get(name='test_party')
        user_two = Profile.objects.get(username='******')
        membership = Membership.objects.get(party=party, profile=user_two)

        self.party_service.remove_member_from_party(membership)

        is_in_party = party.memberships.filter(profile=user_two).exists()

        self.assertFalse(is_in_party)
Esempio n. 12
0
class AddMemberToPartyTestCase(TestCase):
    party_service = PartyService()
    profile_service = ProfileService()

    def setUp(self):
        creator = Profile.objects.create(username='******')
        Profile.objects.create(username='******')

        Party.objects.create(name='test_party', created_by=creator)

    def test_add_member(self):
        party = self.party_service.get(name='test_party')
        user_two = self.profile_service.get(username='******')

        self.party_service.add_member_to_party(party, user_two)

        party_membership = party.memberships.get(profile=user_two)
        actual_membership = Membership.objects.get(party=party,
                                                   profile=user_two)

        self.assertEqual(party_membership, actual_membership)
Esempio n. 13
0
 def __init__(self):
     self.party_service = PartyService()
     self.profile_service = ProfileService()
     self.schedule_service = ScheduleService()
     self.template_order_service = TemplateOrderService()
     self.template_member_service = TemplateMemberService()
Esempio n. 14
0
class TemplatePartyService(Service):
    model = TemplateParty

    TEMPLATE_PREFIX = 'Template'

    def __init__(self):
        self.party_service = PartyService()
        self.profile_service = ProfileService()
        self.schedule_service = ScheduleService()
        self.template_order_service = TemplateOrderService()
        self.template_member_service = TemplateMemberService()

    @transaction.atomic()
    def create(self, name, creator, members=None, food=None):
        if not members:
            members = []

        if not food:
            food = []

        template_party = super(TemplatePartyService,
                               self).create(name=name, created_by=creator)

        self.template_member_service.create(profile=creator,
                                            party=template_party,
                                            is_owner=True)
        for member in members:
            self.template_member_service.create(profile=member,
                                                party=template_party)

        for item in food:
            self.template_order_service.create(party=template_party,
                                               name=item.name,
                                               price=item.price,
                                               quantity=1)

        return template_party

    @transaction.atomic
    def create_from_existing(self, party: Party) -> TemplateParty:
        template_name = self.get_template_name(party)
        template_party = super(TemplatePartyService,
                               self).create(name=template_name,
                                            created_by=party.created_by)

        template_food = {}
        for item in party.orderedfood_set.all():
            order_item = self.template_order_service.create(
                party=template_party,
                name=item.name,
                price=item.price,
                quantity=item.quantity)
            template_food[order_item.name] = order_item

        members = self.party_service.get_party_members(party)
        for member in members:
            template_member = self.template_member_service.create(
                profile=member.profile,
                party=template_party,
                is_owner=member.is_owner)
            for excluded_food in member.excluded_food.all():
                food = template_food[excluded_food.name]
                template_member.excluded_food.add(food)

        party.template = template_party
        party.save()

        return template_party

    def is_active(self, template: model):
        return True if template.state == self.model.ACTIVE else False

    def has_active_parties(self, template: TemplateParty):
        return template.parties.filter(state=Party.ACTIVE).exists()

    def get_template_members(self, template: model):
        return template.template_memberships.all()

    def get_template_ordered_food(self, template: model):
        return template.template_ordered_food.all()

    def add_member_to_template(self, template: model, info: str):
        profile = self.profile_service.get(username=info)

        if not profile:
            raise Profile.DoesNotExist

        if self.template_member_service.is_party_member(profile, template):
            raise MemberAlreadyInPartyException(
                "User {0} (id={1}) is already in {2} (id={3})".format(
                    profile.username, profile.id, template.name, template.id))

        self.template_member_service.grant_membership(template, profile)

    def remove_member_from_template(self, member: Membership):
        self.template_member_service.revoke_membership(member)

    def order_food(self, template: model, food: Food, quantity: int):
        self.template_order_service.create_or_update_order_item(
            template, food.name, food.price, quantity)

    def remove_from_order(self, order_item: OrderedFood):
        self.template_order_service.delete(order_item)

    def set_state(self, template: model, state):
        allowed_states = (TemplateParty.ACTIVE, TemplateParty.INACTIVE)
        if state not in allowed_states:
            raise NoSuchTemplatePartyStateException()

        state_for_periodic_task = True if state == TemplateParty.ACTIVE else False
        self.schedule_service.set_periodic_task_enabled(
            template, state_for_periodic_task)

        template.state = state
        template.save()

    def set_frequency(self, template: model, schedule: Schedule):
        schedule_values = (schedule.minute, schedule.hour,
                           schedule.day_of_week, schedule.day_of_month,
                           schedule.month_of_year)
        kwargs = dict(
            zip(self.schedule_service.CRONTAB_FIELDS, schedule_values))

        crontab_schedule, _ = self.schedule_service.get_or_create_dcbcs(
            **kwargs)

        template.schedule = schedule
        template.save()

    def get_template_name(self, party: Party):
        return '{0} {1}'.format(self.TEMPLATE_PREFIX, party.name)
Esempio n. 15
0
 def __init__(self):
     self.member_service = MemberService()
     self.order_service = OrderService()
     self.profile_service = ProfileService()
Esempio n. 16
0
class PartyService(Service):
    model = Party

    def __init__(self):
        self.member_service = MemberService()
        self.order_service = OrderService()
        self.profile_service = ProfileService()

    def create(self, name, creator, members=None) -> model:
        if not members:
            members = []

        party = super(PartyService, self).create(name=name, created_by=creator)

        self.member_service.create(profile=creator, party=party, is_owner=True)
        for member in members:
            self.member_service.create(profile=member, party=party)

        return party

    @transaction.atomic
    def create_from_template(self, template: TemplateParty) -> model:
        from party_calculator.services.template_party import TemplatePartyService
        template_name = template.name.replace(
            TemplatePartyService.TEMPLATE_PREFIX, '')
        party_name = '{0} | {1}'.format(template_name,
                                        time.strftime("%d.%m.%Y:%H:%M"))

        party = super(PartyService,
                      self).create(name=party_name,
                                   created_by=template.created_by,
                                   template=template)

        party_food = {}
        for order_item in template.template_ordered_food.all():
            item = self.order_service.create(party=party,
                                             name=order_item.name,
                                             price=order_item.price,
                                             quantity=order_item.quantity)
            party_food[item.name] = item

        for template_member in template.template_memberships.all():
            is_owner = True if template_member.profile == party.created_by else False
            member = self.member_service.create(
                profile=template_member.profile,
                party=party,
                is_owner=is_owner)

            for template_excluded_food in template_member.excluded_food.all():
                food = party_food[template_excluded_food.name]
                member.excluded_food.add(food)

        return party

    def set_state(self, party: model, state):
        self.check_is_party_active(party)

        if state not in [x for (x, y) in self.model.states]:
            raise NoSuchPartyStateException()

        party.state = state
        party.save()

    def is_active(self, party: model):
        return True if party.state == self.model.ACTIVE else False

    def has_template(self, party: Party) -> bool:
        return True if party.template else False

    def get_party_members(self, party: model, excluding=None):
        if excluding:
            return party.memberships.exclude(**excluding)
        return party.memberships.all()

    def get_party_profiles(self, party: model, excluding=None):
        if excluding:
            return party.members.exclude(**excluding)
        return party.members.all()

    def get_party_ordered_food(self, party: model):
        return party.orderedfood_set.all()

    def add_member_to_party(self, party: model, profile: Profile):
        self.check_is_party_active(party)

        self.member_service.grant_membership(party, profile)

    def remove_member_from_party(self, member: Membership):
        self.check_is_party_active(member.party)

        self.member_service.revoke_membership(member)

    def order_food(self, party: model, food: Food, quantity: int):
        self.check_is_party_active(party)

        self.order_service.create_or_update_order_item(party, food.name,
                                                       food.price, quantity)

    def remove_from_order(self, order_item: OrderedFood):
        self.check_is_party_active(order_item.party)

        self.order_service.delete(order_item)

    def sponsor_party(self, member: Membership, amount: float):
        self.check_is_party_active(member.party)

        member.total_sponsored += decimal.Decimal(amount)
        member.save()

    def invite_member(self, party: model, info: str):
        self.check_is_party_active(party)

        profile = self.profile_service.get(username=info)

        if not profile:
            raise Profile.DoesNotExist()

        if self.member_service.is_party_member(profile, party):
            raise MemberAlreadyInPartyException(
                "User {0} (id={1}) is already in {2} (id={3})".format(
                    profile.username, profile.id, party.name, party.id))

        join_url = '/party/invite/someID'
        from party_calculator.tasks import send_mail
        send_mail.delay(
            "Party calculator: You are invited to {0}".format(party.name),
            "Proceed this link to join the Party and start becoming drunk\n"
            "{0}{1}".format(WEBSITE_URL, join_url), "admin@{0}".format(HOST),
            [profile.email])

        # We will add member without confirmation for now but check console for a message
        self.add_member_to_party(party, profile)

    def check_is_party_active(self, party: model):
        if not self.is_active(party):
            raise PermissionDenied("You cannot modify inactive party")