Beispiel #1
0
    def post(self, request, format=None):
        needed_fields = ["imsi", "keyword"]
        if not all(i in request.POST for i in needed_fields):
            return Response("Missing Args", status=status.HTTP_400_BAD_REQUEST)

        imsi = request.data['imsi']
        keyword = request.data['keyword']
        callerid = endaga_sub.get_numbers_from_imsi(imsi)[0]
        subscriptions = PromoSubscription.objects.filter(
            contact__imsi__exact=imsi, promo__keyword=keyword)
        if not subscriptions:
            send_sms.delay(callerid, '0000',
                           _("You have no %s subscriptions.") % keyword)
            ret = 'FAIL UNSUBSCRIBE'
        else:
            for item in subscriptions:
                app.control.revoke(str(item.id), terminate=True)
            subscriptions.delete()
            msg = _("You are now unsubscribed from your %s promos.") % keyword
            send_sms.delay(callerid, '0000', msg)
            ret = 'OK UNSUBSCRIBE'

            # we should also create an event
            balance = endaga_sub.get_account_balance(imsi)
            reason = "Promo Cancel Subscription: %s" % keyword
            events.create_sms_event(imsi, balance, 0, reason, '555')

        return Response(ret, status=status.HTTP_200_OK)
Beispiel #2
0
def service_view(request, pk, template_name='services/detail.html'):
    service = get_object_or_404(Service, pk=pk)

    form = MessageForm(request.POST or None)
    sender = request.user.userprofile.contact

    if form.is_valid(
    ) and 'submit' in request.POST and 'message' in request.POST:

        message = Message.objects.create(
            author=sender, message=form.cleaned_data.get('message'))
        message.published_date = timezone.now()
        message.save()
        subscribers = ServiceSubscribers.objects.filter(service_id=service.id)
        for subscriber in subscribers:
            MessageRecipients.objects.create(message=message,
                                             user=subscriber.subscriber)
            send_sms.delay(subscriber.subscriber.callerid, sender.callerid,
                           message.message)
        alerts.success(
            request,
            _("You've successfully broadcasted to "
              "%s's subscribers") % service)

    data = {
        'service': service,
        'script_args': json.dumps(service.script_arguments),
        'form': form
    }
    if service.service_type == 'P':
        data['interval'] = ServiceScheduledTasks.objects.get(
            service=service).get_interval()
    return render(request, template_name, data)
Beispiel #3
0
    def post(self, request):
        """ POST method for registering contact """

        needed_fields = ["imsi", "callerid"]
        # needed_fields = ["imsi", "callerid", "lastname", "firstname"]
        if all(i in request.POST for i in needed_fields):

            # if it is not in args, let's replace with dummy data
            fields = ['firstname', 'lastname', 'birthdate', 'address']
            dummy = [
                'User', request.data['callerid'],
                timezone.now(), 'Diliman, QC'
            ]
            # for i in xrange(0, len(fields)):
            #    if fields[i] not in request.data:
            #        request.data[fields[i]] = dummy[i]

            new_contact = Contact()
            new_contact.imsi = request.data['imsi']
            new_contact.callerid = request.data['callerid']
            new_contact.save()

            send_sms.delay(request.data['callerid'], '0000',
                           _("You are now listed in the VBTS database."))

            return Response('OK CREATED', status=status.HTTP_200_OK)

        return Response("ERROR", status=status.HTTP_400_BAD_REQUEST)
Beispiel #4
0
def message_send(request, template_name='messages/form.html'):
    form = MessageForm(request.POST or None)
    if form.is_valid():
        message = form.save(commit=False)
        message.author = request.user.userprofile.contact
        message.published_date = timezone.now()
        message.save()

        if form.cleaned_data.get('to_all'):
            contacts = Contact.objects.filter(~Q(imsi=message.author.imsi))
        else:
            contacts = form.cleaned_data.get('recipients')

        for contact in contacts:
            recipient = MessageRecipients.objects.create(
                message=message, user=contact)
            recipient.save()
            send_sms.delay(contact.callerid,
                           message.author.callerid,
                           message.message)
        alerts.success(
            request,
            _("You've successfully sent the message '%s'.") %
            message.message)
        return message_list(request)
    return render(request, template_name, {'form': form})
Beispiel #5
0
def add_promo(request, pk=None, template_name='contacts/addpromo_form.html'):
    """
        This function ties a promo (creates a promo subscription)
        to a SIM card (Contact)
    Args:
        request:
        pk: primary key passed is the SIM card's callerid
        template_name:

    Returns:

    """
    if pk:
        contact = get_object_or_404(Contact, callerid=pk)
    else:
        contact = None
    form = ContactAddPromoForm(request.POST or None, contact=contact)

    if form.is_valid():
        instance = form.save(commit=False)
        promo = form.cleaned_data.get('promo')
        contact = form.cleaned_data.get('contact')
        instance.local_sms = promo.local_sms
        instance.local_call = promo.local_call
        instance.outside_sms = promo.outside_sms
        instance.outside_call = promo.outside_call
        instance.date_expiration = timezone.now() + timedelta(promo.validity)
        instance.save()

        send_sms.delay(
            contact.callerid, '0000',
            _('You are automatically subscribed to %(promo)s promo. '
              'To opt out, text REMOVE %(keyword)s to 555.') %
            ({
                'promo': promo.name,
                'keyword': promo.keyword
            }))
        purge_entry.apply_async(eta=instance.date_expiration,
                                args=[instance.pk],
                                task_id=str(instance.pk))

        # we should also create an event
        balance = endaga_sub.get_account_balance(contact.imsi)
        reason = "Promo Auto Subscription: %s" % promo.keyword
        events.create_sms_event(contact.imsi, balance, 0, reason, '555')

        alerts.success(
            request,
            _("You've successfully added '%(promo)s' promo to "
              "contact '%(contact)s.'") % ({
                  'promo': promo,
                  'contact': contact
              }))
        return contact_list(request)
    return render(request, template_name, {'form': form})
Beispiel #6
0
    def post(self, request, format=None):
        needed_fields = ["keyword", "imsi"]
        if not all(i in request.POST for i in needed_fields):
            return Response("Missing Args", status=status.HTTP_400_BAD_REQUEST)

        imsi = request.data['imsi']
        keyword = request.data['keyword']
        callerid = endaga_sub.get_numbers_from_imsi(imsi)[0]

        try:
            promo = Promo.objects.get(keyword__exact=keyword)
            msg = promo.description
        except BaseException:
            msg = "You have entered an invalid promo keyword."
        send_sms.delay(callerid, '0000', msg)

        return Response('OK', status=status.HTTP_200_OK)
Beispiel #7
0
def inforequest_send(request, pk, template_name='inforequests/send.html'):
    service = get_object_or_404(Service, pk=pk)
    form = MessageForm(request.POST or None)
    if form.is_valid():
        servicemessages = form.save(commit=False)
        servicemessages.service = service
        servicemessages.sender = request.user.userprofile.contact
        servicemessages.date = timezone.now()
        servicemessages.save()

        for subscriber in service.subscribers.all():
            send_sms.delay(subscriber.callerid,
                           servicemessages.sender.callerid,
                           servicemessages.message)
        alerts.success(request, _("You've successfully sent \
            the message '%(msg)s' to %(keyword)s's subscribers.") % ({
            'msg': servicemessages.message,
            'keyword': service.keyword
        }))
    return render(request, template_name, {'service': service, 'form': form})
Beispiel #8
0
def promo_delete_subscription(request,
                              pk,
                              template_name='promos/subscription_'
                              'confirm_delete.html'):
    subscription = get_object_or_404(PromoSubscription, pk=pk)
    if request.method == 'POST':
        revoke(str(pk), terminate=True)
        msg = _("You were automatically unsubscribed from your %s promo."
                ) % subscription.promo.keyword
        send_sms.delay(subscription.contact.callerid, '0000', msg)

        # we should also create an event
        balance = endaga_sub.get_account_balance(subscription.contact.imsi)
        reason = "Promo Cancel Subscription: %s" % subscription.promo.keyword
        events.create_sms_event(subscription.contact.imsi, balance, 0, reason,
                                '555')

        subscription.delete()
        return redirect(request.GET.get('from', 'promos'))
    return render(request, template_name, {'subscription': subscription})
Beispiel #9
0
    def post(self, request):
        """ POST method for submitting a report """
        needed_fields = ["imsi", "keyword", "message"]
        if not all(i in request.POST for i in needed_fields):
            return Response("ERROR: Missing arguments.",
                            status=status.HTTP_400_BAD_REQUEST)

        imsi = request.data['imsi']
        try:
            subscriber = Contact.objects.get(imsi__exact=imsi)
        except BaseException:
            send_sms.delay(
                endaga_sub.get_numbers_from_imsi(imsi)[0], '0000',
                _("You are currently not registered to the BTS. "
                  "Please register."))
            return Response("ERROR: Not registered subscriber.",
                            status=status.HTTP_400_BAD_REQUEST)

        try:
            report = Report.objects.filter(
                Q(keyword=request.data['keyword'].upper()) & Q(status='P'))[0]
        except BaseException:
            send_sms.delay(
                subscriber.callerid, '0000',
                _("Sorry we can't process your request. "
                  "Invalid keyword."))
            return Response("ERROR: Invalid keyword.",
                            status=status.HTTP_400_BAD_REQUEST)

        new_report = ReportMessages()
        new_report.sender = subscriber
        new_report.report = report
        new_report.message = request.data['message']
        new_report.date = timezone.now()
        new_report.save()

        send_sms.delay(
            subscriber.callerid, '0000',
            _("You have successfully sent a report to %s.") % report.keyword)
        for manager in report.managers.all():
            send_sms.delay(
                manager.callerid, '0000',
                _("New report from %(manager)s. "
                  "%(keyword)s:%(msg)s") % ({
                      'manager': manager.callerid,
                      'keyword': report.keyword,
                      'msg': new_report.message
                  }))

        return Response('OK CREATED', status=status.HTTP_200_OK)
Beispiel #10
0
    def post(self, request, format=None):
        """ POST method to send a message to a circle or UE """

        needed_fields = ["imsi", "name", "msg"]
        if not all(i in request.POST for i in needed_fields):
            return Response("", status=status.HTTP_400_BAD_REQUEST)

        try:
            sender = Contact.objects.get(imsi=request.data['imsi'])
            group = Group.objects.get(name=request.data['name'])
            members = GroupMembers.objects.filter(group_id=group.id)
        except BaseException:
            return Response("Args failed", status=status.HTTP_400_BAD_REQUEST)

        # Check that sender is part of the group nor owner
        if not members.filter(user=sender) \
                and group.owner.imsi != request.data['imsi']:
            send_sms.delay(sender.callerid, '0000',
                           _("FORBIDDEN. You are not a member of this group."))
            return Response("Forbidden", status=status.HTTP_403_FORBIDDEN)

        message = Message.objects.create(author=sender,
                                         message=request.data['msg'])
        message.published_date = timezone.now()
        message.save()

        failed = []
        invalid_callerid = False

        for member in members:
            recipient = MessageRecipients.objects.create(message=message,
                                                         user=member.user)
            try:
                send_sms.delay(recipient.user.callerid, sender.callerid,
                               message.message)
                recipient.save()

            except openbts.exceptions.InvalidRequestError:
                invalid_callerid = True
                failed.append(recipient.user.callerid)

        if invalid_callerid:
            send_sms.delay(sender.callerid, '0000',
                           _("Failed to send your message to: %s.") % failed)
            return Response("", status=status.HTTP_400_BAD_REQUEST)
        else:
            send_sms.delay(sender.callerid, '0000',
                           _("Successfully sent your message to the group."))
            return Response('OK SEND', status=status.HTTP_200_OK)
Beispiel #11
0
    def post(self, request, format=None):
        """ POST method for deleting a group """

        if not ("name" in request.POST or "imsi" in request.POST):
            return Response("ERROR", status=status.HTTP_400_BAD_REQUEST)

        requester = Contact.objects.get(imsi=request.data['imsi'])

        try:
            group = Group.objects.get(name__exact=request.data['name'],
                                      owner__imsi=request.data['imsi'])
            group.members.clear()
            group.delete()
            send_sms.delay(
                requester.callerid, '0000',
                _("Successfully deleted group %s.") % request.data['name'])
            return Response('DELETE OK', status=status.HTTP_200_OK)
        except BaseException:
            send_sms.delay(
                requester.callerid, '0000',
                _("Failed to delete group %s.") % request.data['name'])
            return Response('DELETE FAIL', status=status.HTTP_400_BAD_REQUEST)
Beispiel #12
0
def circle_broadcast(request, pk=None, template_name='circles/sms.html'):
    form = BroadcastForm(request.POST or None, circle_id=pk)
    sender = request.user.userprofile.contact

    if form.is_valid():
        message = Message.objects.create(author=sender,
                                         message=form.cleaned_data.get(
                                             'message'))
        message.published_date = datetime.now()
        message.save()
        for circle in request.POST.getlist('circles'):
            members = CircleUsers.objects.filter(circle_id=circle)
            for member in members:
                MessageRecipients.objects.create(message=message,
                                                 user=member.user)
                send_sms.delay(member.user.callerid,
                               sender.callerid,
                               message.message)
            alerts.success(request, _("You've successfully broadcasted \
                the message."))
        return circle_list(request)
    return render(request, template_name, {'form': form})
Beispiel #13
0
def circle_view(request, pk, template_name='circles/detail.html'):
    circle = get_object_or_404(Circle, pk=pk)
    form = MessageForm(request.POST or None)
    sender = request.user.userprofile.contact

    if form.is_valid():

        message = Message.objects.create(author=sender,
                                         message=form.cleaned_data.get(
                                             'message'))
        message.published_date = datetime.now()
        message.save()
        members = CircleUsers.objects.filter(circle_id=circle.id)
        for member in members:
            MessageRecipients.objects.create(message=message,
                                             user=member.user)
            send_sms.delay(member.user.callerid,
                           sender.callerid,
                           message.message)
        alerts.success(
            request, _("You've successfully broadcasted to  %s's members.") %
            circle.name)
    return render(request, template_name, {'circle': circle, 'form': form})
Beispiel #14
0
    def post(self, request):
        """ POST method for subscribing to a service """
        needed_fields = ["imsi", "keyword"]
        if not all(i in request.POST for i in needed_fields):
            return Response("ERROR: Missing arguments.",
                            status=status.HTTP_400_BAD_REQUEST)

        imsi = request.data['imsi']

        try:
            subscriber = Contact.objects.get(imsi__exact=imsi)
        except BaseException:
            send_sms.delay(
                endaga_sub.get_numbers_from_imsi(imsi)[0], '0000',
                _("You are currently not registered to the BTS. "
                  "Please register."))
            return Response("ERROR: Not registered subscriber.",
                            status=status.HTTP_404_NOT_FOUND)

        try:
            service = Service.objects.filter(
                keyword=request.data['keyword'].upper(),
                service_type='P',
                status='P')[0]
        except BaseException:
            send_sms.delay(
                subscriber.callerid, '0000',
                _("Sorry we can't process your request. "
                  "Invalid keyword."))
            return Response("ERROR: Invalid keyword.",
                            status=status.HTTP_400_BAD_REQUEST)

        is_subscribed = ServiceSubscribers.objects. \
            filter(service=service, subscriber=subscriber).exists()

        if is_subscribed:
            send_sms.delay(subscriber.callerid, '0000',
                           _("You are subscribed to %s.") % service.name)
            return Response('OK STATUS - SUBSCRIBED',
                            status=status.HTTP_200_OK)

        else:
            send_sms.delay(subscriber.callerid, '0000',
                           _("You are not subscribed to %s.") % service.name)
            return Response('OK STATUS - NOT SUBSCRIBED',
                            status=status.HTTP_200_OK)
Beispiel #15
0
    def post(self, request):
        """ POST method for opting out from a service """
        needed_fields = ["imsi", "keyword"]
        if not all(i in request.POST for i in needed_fields):
            return Response("ERROR: Missing arguments.",
                            status=status.HTTP_400_BAD_REQUEST)

        imsi = request.data['imsi']
        keyword = request.data['keyword']

        try:
            subscriber = Contact.objects.get(imsi__exact=imsi)
        except BaseException:
            send_sms.delay(
                endaga_sub.get_numbers_from_imsi(imsi)[0], '0000',
                _("You are currently not registered to the BTS. "
                  "Please register."))
            return Response("ERROR: Not registered subscriber.",
                            status=status.HTTP_400_BAD_REQUEST)

        try:
            subscription = ServiceSubscribers.objects.filter(
                service__keyword__exact=keyword,
                subscriber__imsi__exact=request.data['imsi'])[0]
            subscription.delete()
            send_sms.delay(
                subscriber.callerid, '0000',
                _("You have successfully unsubscribed to %s.") %
                subscription.service.name)
            return Response('OK UNSUBSCRIBED', status=status.HTTP_200_OK)
        except BaseException:
            send_sms.delay(
                subscriber.callerid, '0000',
                _("You are not currently subscribed to the service."))
            return Response("ERROR: You are not currently subscribed to "
                            "the %s service." % keyword,
                            status=status.HTTP_400_BAD_REQUEST)
Beispiel #16
0
    def post(self, request):
        """ POST method to send message to service's subscribers. """
        needed_fields = ["imsi", "keyword", "message"]
        if not all(i in request.POST for i in needed_fields):
            return Response("ERROR: Missing arguments.",
                            status=status.HTTP_400_BAD_REQUEST)

        imsi = request.data['imsi']
        keyword = request.data['keyword']
        try:
            service = Service.objects.filter(keyword=keyword.upper(),
                                             status='P')[0]
        except BaseException:
            send_sms.delay(
                endaga_sub.get_numbers_from_imsi(imsi)[0], '0000',
                _("Sorry we can't process your request. "
                  "Invalid service."))
            return Response("ERROR: Invalid service.",
                            status=status.HTTP_400_BAD_REQUEST)

        # check first if sender is the service manager
        # if so, propagate message to all service subscribers
        if service.managers.filter(imsi=request.data['imsi']).exists():
            for subscriber in service.subscribers.all():
                send_sms.delay(subscriber.callerid, '0000',
                               _("ANNOUNCEMENT: %s") % request.data['message'])
            return Response('ANNOUNCEMENT SENT', status=status.HTTP_200_OK)

        else:
            send_sms.delay(
                endaga_sub.get_numbers_from_imsi(imsi)[0], '0000',
                _("You are not allowed to send message to %s's "
                  "subscribers.") % keyword)
            return Response("ERROR: No administrative privileges to send to "
                            "this %s's subscribers." % keyword,
                            status=status.HTTP_400_BAD_REQUEST)
Beispiel #17
0
def simple_upload(request, template_name='promos/upload_csv.html'):
    csv_subs_len = 2
    csv_promo_len = 12
    fail = False
    promo = True
    contact = True
    page = 'promo_upload_csv'

    if request.method == 'POST':
        form = DocumentForm(request.POST, request.FILES)
        if form.is_valid():
            myfile = request.FILES['docfile']
            actobj = form.cleaned_data.get(
                'action') + form.cleaned_data.get('object')

            reader = csv.reader(io.StringIO(myfile.read().decode('utf-8')))
            headers = next(reader)  # handle row header
            if actobj == '11':  # Create promos
                if len(headers) < csv_promo_len:
                    fail = True
                    alerts.warning(request, _(
                        "Missing required fields. Check your CSV file again."
                    ))
                for row in reader:
                    if len(row) < csv_promo_len:
                        break  # do nothing
                    try:
                        Promo.objects.create(
                            author=request.user,
                            name=row[0],
                            description=row[1],
                            price=row[2],
                            promo_type=row[3],
                            keyword=row[4],
                            validity=row[5],
                            local_sms=row[6],
                            local_call=row[7],
                            globe_sms=row[8],
                            globe_call=row[9],
                            outside_sms=row[10],
                            outside_call=row[11])
                    except Exception as e:
                        fail = True
                        alerts.warning(
                            request, _(
                                'Duplicate entries found in CSV file. %s' %
                                e))

            elif actobj == '12':  # Create promo subscriptions
                if len(headers) < csv_subs_len:
                    fail = True
                    alerts.warning(request, _(
                        "Missing required fields. Check your CSV file again."
                    ))
                for row in reader:
                    if len(row) < csv_subs_len:
                        break
                    try:
                        promo = Promo.objects.get(keyword=row[0])
                    except Promo.DoesNotExist:
                        promo = None
                    try:
                        contact = Contact.objects.get(callerid=row[1])
                    except Contact.DoesNotExist:
                        fail = True
                        contact = None

                    if promo and contact:
                        try:
                            instance = PromoSubscription.objects.create(
                                promo=promo,
                                contact=contact,
                                date_expiration=timezone.now() + timedelta(
                                    promo.validity),
                                local_sms=promo.local_sms,
                                local_call=promo.local_call,
                                globe_sms=promo.globe_sms,
                                globe_call=promo.globe_call,
                                outside_sms=promo.outside_sms,
                                outside_call=promo.outside_call)
                            purge_entry.apply_async(
                                eta=instance.date_expiration,
                                args=[instance.pk],
                                task_id=str(instance.pk))
                            send_sms.delay(
                                contact.callerid,
                                '0000',
                                _(
                                    'You are automatically subscribed to %(promo)s promo '
                                    'valid for %(validity)s day(s). '
                                    'To opt out, text REMOVE %(keyword)s to 555. '
                                    'For more info, text INFO %(keyword)s to 555.') % ({
                                        'promo': promo.name,
                                        'validity': promo.validity,
                                        'keyword': promo.keyword}))
                            # we should also create an event
                            balance = endaga_sub.get_account_balance(
                                contact.imsi)
                            reason = "Promo Auto Subscription: %s" % promo.keyword
                            events.create_sms_event(contact.imsi, balance,
                                                    0, reason, '555')
                        except BaseException:
                            pass

            elif actobj == '21':  # Delete promo
                pass
                # for row in reader:
                #     Promo.objects.filter(keyword=row[6]).delete()
                # # TODO: Do we also delete exisiting subscriptions?
            elif actobj == '22':  # Delete promo subscriptions
                for row in reader:
                    subscriptions = PromoSubscription.objects.filter(
                        promo__keyword__exact=row[0],
                        contact__callerid__exact=row[1])
                    for item in subscriptions:
                        app.control.revoke(str(item.id), terminate=True)
                    subscriptions.delete()
            else:
                pass

            myfile.close()
            if not fail:
                alerts.success(request, _(
                    "Batch operation completed successfully."))
                page = 'promos'
            else:
                if not contact:
                    alerts.warning(
                        request,
                        _("Operation failed. Contact does not exist.")
                    )
                elif not promo:
                    alerts.warning(
                        request,
                        _("Operation failed. Promo does not exist.")
                    )
                else:
                    alerts.warning(
                        request,
                        _("Operation failed. Unknown error.")
                    )
            return redirect(page)
    else:
        form = DocumentForm()
    return render(request, template_name, {'form': form})
Beispiel #18
0
    def post(self, request, format=None):
        needed_fields = ["imsi"]
        if not all(i in request.POST for i in needed_fields):
            return Response("Missing Args", status=status.HTTP_400_BAD_REQUEST)

        imsi = request.data['imsi']
        keyword = request.data['keyword']
        callerid = endaga_sub.get_numbers_from_imsi(imsi)[0]

        if not keyword:
            subscriptions = PromoSubscription.objects.filter(
                contact__imsi__exact=imsi). \
                order_by('date_expiration')
        else:
            subscriptions = PromoSubscription.objects.filter(
                contact__imsi__exact=imsi, promo__keyword=keyword). \
                order_by('date_expiration')
        if not subscriptions:
            send_sms.delay(callerid, '0000',
                           _("You have no %s subscriptions.") % keyword)

        else:
            msg = ""

            try:
                tz = Config.objects.get(key='timezone').value
            except Config.DoesNotExist:
                tz = pytz_timezone('Asia/Manila')

            for item in subscriptions:
                msg += "Your %s promo status: \\n" % item.promo.keyword
                expiry = item.date_expiration. \
                    astimezone(tz).strftime("%m/%d/%y %I:%M%p")

                if item.promo.promo_type == 'D' or item.promo.promo_type == 'G':
                    if item.local_sms:
                        msg += "%s local texts discount price: P%s\\n" % (
                            item.promo.keyword, mc_to_float(item.local_sms))
                    if item.local_call:
                        msg += "%s local call/min discount price: P%s\\n" % (
                            item.promo.keyword, mc_to_float(item.local_call))
                    if item.globe_sms:
                        msg += "%s Globe texts discount price: P%s\\n" % (
                            item.promo.keyword, mc_to_float(item.globe_sms))
                    if item.globe_call:
                        msg += "%s Globe call/min discount price: P%s\\n" % (
                            item.promo.keyword, mc_to_float(item.globe_call))
                    if item.outside_sms:
                        msg += "%s outside texts discount price: P%s\\n" % (
                            item.promo.keyword, mc_to_float(item.outside_sms))
                    if item.outside_call:
                        msg += "%s outside call/min discount price: P%s\\n" % (
                            item.promo.keyword, mc_to_float(item.outside_call))
                elif item.promo.promo_type == 'B':
                    if item.local_sms:
                        msg += "%s local texts: %s\\n" % (item.promo.keyword,
                                                          item.local_sms)
                    if item.local_call:
                        msg += "%s local call mins: %s\\n" % (
                            item.promo.keyword, item.local_call)
                    if item.globe_sms:
                        msg += "%s Globe texts: %s\\n" % (item.promo.keyword,
                                                          item.globe_sms)
                    if item.globe_call:
                        msg += "%s Globe call mins: %s\\n" % (
                            item.promo.keyword, item.globe_call)
                    if item.outside_sms:
                        msg += "%s outside texts: %s\\n" % (item.promo.keyword,
                                                            item.outside_sms)
                    if item.outside_call:
                        msg += "%s outside call mins: %s\\n" % (
                            item.promo.keyword, item.outside_call)
                elif item.promo.promo_type == 'U':
                    if item.local_sms:
                        msg += "%s unli local texts\\n" % item.promo.keyword
                    if item.local_call:
                        msg += "%s unli local calls\\n" % item.promo.keyword
                    if item.globe_sms:
                        msg += "%s unli Globe texts\\n" % item.promo.keyword
                    if item.globe_call:
                        msg += "%s unli Globe calls\\n" % item.promo.keyword
                    if item.outside_sms:
                        msg += "%s unli outside texts\\n" % item.promo.keyword
                    if item.outside_call:
                        msg += "%s unli outside calls\\n" % item.promo.keyword
                msg += "Exp: %s\\n" % expiry

            send_sms.delay(callerid, '0000', msg[:-2])

        return Response('OK', status=status.HTTP_200_OK)
Beispiel #19
0
    def post(self, request):
        needed_fields = ["imsi", "keyword"]
        if not all(i in request.POST for i in needed_fields):
            return Response("Missing Args", status=status.HTTP_400_BAD_REQUEST)

        imsi = request.data['imsi']
        keyword = request.data['keyword']

        try:
            subscriber = Contact.objects.get(imsi__exact=imsi)
        except BaseException:  # subscriber not found in Contacts table
            send_sms.delay(
                endaga_sub.get_numbers_from_imsi(imsi)[0], '0000',
                _("You are not listed in the PCARI-VBTS database. "
                  "Please register."))
            return Response("Not Found", status=status.HTTP_404_NOT_FOUND)

        # We put code to optionally limit promo subscriptions
        # this depends on the limit type declared in the configs

        try:
            limit_type = Config.objects.get(key='promo_limit_type').value
        except Config.DoesNotExist:
            limit_type = 'NA'

        try:
            max_promo_subscription = int(
                Config.objects.get(key='max_promo_subscription').value)
        except Config.DoesNotExist:
            max_promo_subscription = 1

        try:
            min_balance_required = float(
                Config.objects.get(key='min_balance_required').value)
        except Config.DoesNotExist:
            min_balance_required = 0

        # type A: Limit number of subscription per promo
        if limit_type == 'A':
            count = PromoSubscription.objects.filter(
                promo__keyword__exact=keyword, contact=subscriber).count()
            if count >= max_promo_subscription:
                send_sms.delay(subscriber.callerid, '0000',
                               _("You have to many promo subscriptions."))
                return Response("Too Many Subscriptions",
                                status=status.HTTP_403_FORBIDDEN)

        # type B: Limit number of subscription for all promos
        elif limit_type == 'B':
            count = PromoSubscription.objects.filter(
                contact=subscriber).count()
            if count >= max_promo_subscription:
                send_sms.delay(subscriber.callerid, '0000',
                               _("You have to many promo subscriptions."))
                return Response("Too Many Subscriptions",
                                status=status.HTTP_403_FORBIDDEN)
        else:
            pass  # proceed as usual

        try:
            promo = Promo.objects.get(keyword__exact=keyword)
        except BaseException:  # bad promo keyword
            send_sms.delay(subscriber.callerid, '0000',
                           _("You made a bad promo request."))
            return Response("Bad promo request",
                            status=status.HTTP_400_BAD_REQUEST)

        # check account balance first
        balance = endaga_sub.get_account_balance(imsi)
        if balance - promo.price < min_balance_required:
            send_sms.delay(
                subscriber.callerid, '0000',
                _("You do not have sufficient balance to subscribe "
                  "to the %s promo.") % promo.keyword)
            return Response("Insufficient balance",
                            status=status.HTTP_402_PAYMENT_REQUIRED)

        # user passes above check, has enough balance, so sign him up!
        new_subscription = PromoSubscription()
        new_subscription.promo = promo
        new_subscription.contact = subscriber
        # save time as UTC in database
        new_subscription.date_expiration = timezone.now() + timedelta(
            promo.validity)
        new_subscription.local_sms = promo.local_sms
        new_subscription.local_call = promo.local_call
        new_subscription.globe_sms = promo.globe_sms
        new_subscription.globe_call = promo.globe_call
        new_subscription.outside_sms = promo.outside_sms
        new_subscription.outside_call = promo.outside_call
        new_subscription.save()

        # finally, deduct promo.price from subscriber's balance
        # price is expressed in millicents
        endaga_sub.subtract_credit(imsi, str(promo.price))

        try:
            tz = Config.objects.get(key='timezone').value
        except Config.DoesNotExist:
            tz = pytz_timezone('Asia/Manila')

        # present time to subscriber according to defined timezone
        expiry = new_subscription.date_expiration.astimezone(tz). \
            strftime("%m/%d/%y %I:%M%p")

        # and then lets inform the subscriber
        send_sms.delay(
            subscriber.callerid, '0000',
            _("You are now subscribed to %(keyword)s valid "
              "until %(expiry)s.") % ({
                  'keyword': promo.keyword,
                  'expiry': expiry
              }))

        # and then create a purge task
        # let's use the PK as the task_id, so that we dont have to create
        # a new field to store the id. this might be OK for now.
        purge_entry.apply_async(eta=new_subscription.date_expiration,
                                args=[new_subscription.pk],
                                task_id=str(new_subscription.pk))

        # we should also create an event
        reason = "Promo subscription: %s" % promo.keyword
        events.create_sms_event(subscriber.imsi, balance, promo.price, reason,
                                '555')

        return Response('OK SUBSCRIBE', status=status.HTTP_200_OK)
Beispiel #20
0
    def post(self, request):
        """ POST method for creating a group """

        needed_fields = ["imsi", "name", "mems"]
        if not all(i in request.POST for i in needed_fields):
            return Response('ERROR', status=status.HTTP_400_BAD_REQUEST)

        requester = Contact.objects.get(imsi=request.data['imsi'])

        # We put code to optionally the number of groups that a user can
        # create. This depends on the max number declared in the configs

        max_groups_per_subscriber = Config.objects.get(
            key='max_groups_per_subscriber').value
        count = Group.objects.filter(owner=requester).count()
        if max_groups_per_subscriber == 'NA':
            pass  # unlimited, do nothing
        elif count >= int(max_groups_per_subscriber):
            send_sms.delay(
                requester.callerid, '0000',
                _("You have too many groups and have exceeded the"
                  " allowed limits."))
            return Response("Too many groups",
                            status=status.HTTP_403_FORBIDDEN)

        # TODO: Validate when empty members are passed
        # members are passed in this format: 'Num1,Num2,Num3,Num4,Num5'
        if not request.data['mems']:
            send_sms.delay(requester.callerid, '0000',
                           _("You did not input any member contact numbers."))
            return Response("Empty Mem Fields",
                            status=status.HTTP_400_BAD_REQUEST)

        try:
            new_group = Group()
            new_group.owner = requester
            # To all caps or not to all caps?
            new_group.name = request.data['name'].upper()
            new_group.save()
        except BaseException:
            # unique_together constaint failed, among other things
            send_sms.delay(requester.callerid, '0000',
                           "Failed to create group %s." % request.data['name'])
            return Response('Constraint Failed',
                            status=status.HTTP_400_BAD_REQUEST)

        mems = request.data['mems']
        invalid = add_group_members(mems, new_group)

        send_sms.delay(
            new_group.owner.callerid, '0000',
            _("Your group %s has been successfully created.") % new_group.name)
        if invalid:
            send_sms.delay(
                new_group.owner.callerid, '0000',
                _("Failed to add the following to group "
                  "%(group)s. %(invalid)s") % ({
                      'group': new_group.name,
                      'invalid': str(invalid)
                  }))
        return Response('OK CREATED', status=status.HTTP_200_OK)
Beispiel #21
0
    def post(self, request):
        """ POST method for subscribing to a service """
        needed_fields = ["imsi", "keyword"]
        if not all(i in request.POST for i in needed_fields):
            return Response("ERROR: Missing arguments.",
                            status=status.HTTP_400_BAD_REQUEST)

        imsi = request.data['imsi']

        try:
            subscriber = Contact.objects.get(imsi__exact=imsi)
        except BaseException:
            send_sms.delay(
                endaga_sub.get_numbers_from_imsi(imsi)[0], '0000',
                _("You are currently not registered to the BTS. "
                  "Please register."))
            return Response("ERROR: Not registered subscriber.",
                            status=status.HTTP_400_BAD_REQUEST)

        try:
            service = Service.objects.filter(
                keyword=request.data['keyword'].upper(),
                service_type='P',
                status='P')[0]
        except BaseException:
            send_sms.delay(
                subscriber.callerid, '0000',
                _("Sorry we can't process your request. "
                  "Invalid keyword."))
            return Response("ERROR: Invalid keyword.",
                            status=status.HTTP_400_BAD_REQUEST)

        is_duplicate = ServiceSubscribers.objects. \
            filter(service=service, subscriber=subscriber).exists()

        if is_duplicate:
            send_sms.delay(
                subscriber.callerid, '0000',
                _("You are already subscribed to %s.") % service.name)
            return Response('OK ALREADY SUBSCRIBED', status=status.HTTP_200_OK)

        else:
            # check if subscriber has enough balance
            balance = endaga_sub.get_account_balance(imsi)
            if balance - service.price < 0:
                send_sms.delay(
                    subscriber.callerid, '0000',
                    _("You do not have sufficient balance to "
                      "subscribe to %s.") % service.name)
                return Response("Insufficient balance",
                                status=status.HTTP_402_PAYMENT_REQUIRED)

            # user passes above check, has enough balance, so sign him up!
            new_subscription = ServiceSubscribers(subscriber=subscriber,
                                                  service=service)
            new_subscription.date_joined = timezone.now()
            new_subscription.save()
            # finally, deduct service.price from subscriber's balance
            # price is expressed in millicents
            endaga_sub.subtract_credit(imsi, str(service.price))

            send_sms.delay(
                subscriber.callerid, '0000',
                _("You have successfully subscribed to %s.") % service.name)
            return Response('OK SUBSCRIBED', status=status.HTTP_200_OK)
Beispiel #22
0
    def post(self, request):
        """ POST method for creating a group """

        needed_fields = ["imsi", "name", "mems"]
        if not all(i in request.POST for i in needed_fields):
            return Response('ERROR', status=status.HTTP_400_BAD_REQUEST)

        requester = Contact.objects.get(imsi=request.data['imsi'])
        mems = request.data['mems']

        # TODO: Validate when empty members are passed
        # members are passed in this format: 'Num1,Num2,Num3,Num4,Num5'
        if not request.data['mems']:
            send_sms.delay(requester.callerid, '0000',
                           "You did not input any member contact numbers.")
            return Response("Empty Mem Fields",
                            status=status.HTTP_400_BAD_REQUEST)

        try:
            group = Group.objects.get(name__exact=request.data['name'],
                                      owner__imsi=request.data['imsi'])
        except BaseException:
            send_sms.delay(
                requester.callerid, '0000',
                _("Requested group %s does not exist.") % request.data['name'])
            return Response('ACCESS GROUP FAIL',
                            status=status.HTTP_400_BAD_REQUEST)

        delta = timezone.now() - group.last_modified

        try:
            group_edit_interval = Config.objects.get(
                key='group_edit_interval').value
        except Config.DoesNotExist:
            group_edit_interval = 30

        if delta.days < group_edit_interval:
            send_sms.delay(
                requester.callerid, '0000',
                _("You can only edit the group %s once in every %s days.") %
                (request.data['name'], group_edit_interval))
            return Response('GROUP EDIT LIMIT EXCEEDED',
                            status=status.HTTP_400_BAD_REQUEST)

        else:
            group.members.clear()  # clear existing group members first
            group.save()  # then add the new set of members
            invalid = add_group_members(mems, group)

        send_sms.delay(
            group.owner.callerid, '0000',
            _("Your group %s has been successfully edited.") % group.name)
        if invalid:
            send_sms.delay(
                group.owner.callerid, '0000',
                _("However, we failed to add the following to "
                  "group %(group)s. %(invalid)s") % ({
                      'group': group.name,
                      'inavlid': str(invalid)
                  }))
        return Response('OK EDIT', status=status.HTTP_200_OK)