def validate(self, attrs):
        """
        Validate sms campaign form
        """
        request = self.context['request']

        if request.method == 'POST':
            name_count = SMSCampaign.objects.filter(name=attrs.get('name'),
                                                    user=request.user).count()
            if name_count != 0:
                raise serializers.ValidationError("The SMS Campaign name duplicated!")

        if not user_dialer_setting(request.user):
            raise serializers.ValidationError("Your settings are not configured properly, Please contact the administrator.")

        if check_sms_dialer_setting(request, check_for="smscampaign"):
            raise serializers.ValidationError("Too many sms campaigns. Max allowed %s"
                                              % dialer_setting_limit(request, limit_for="smscampaign"))

        frequency = attrs.get('frequency')
        if frequency:
            if check_sms_dialer_setting(request, check_for="smsfrequency", field_value=int(frequency)):
                raise serializers.ValidationError("Frequency limit of %s exceeded."
                                                  % dialer_setting_limit(request, limit_for="smsfrequency"))

        maxretry = attrs.get('maxretry')
        if maxretry:
            if check_sms_dialer_setting(request, check_for="smsretry", field_value=int(maxretry)):
                raise serializers.ValidationError("Retries limit of %s exceeded."
                                                  % dialer_setting_limit(request, limit_for="smsretry"))

        return attrs
Пример #2
0
    def add_view(self, request, extra_context=None):
        """Override django admin add_view method for checking the dialer
        setting limit

        **Logic Description**:

            * Before adding a contact, check the dialer setting limit if
              applicable to the user. If matched, the user will be
              redirected to the contact list
        """
        # Check dialer setting limit
        if request.user and request.method == 'POST':
            # check Max Number of subscribers per campaign
            if check_dialer_setting(request, check_for="contact"):
                msg = _("you have too many contacts per campaign. you are allowed a maximum of %(limit)s")\
                    % {'limit': dialer_setting_limit(request, limit_for="contact")}
                messages.error(request, msg)

                # campaign limit reached
                frontend_send_notification(request, NOTIFICATION_NAME.campaign_limit_reached)
                return HttpResponseRedirect(reverse(
                    "admin:dialer_campaign_contact_changelist"))

        ctx = {}
        return super(ContactAdmin, self).add_view(request, extra_context=ctx)
Пример #3
0
    def add_view(self, request, extra_context=None):
        """Override django admin add_view method for checking the dialer
        setting limit

        **Logic Description**:

            * Before adding a contact, check the dialer setting limit if
              applicable to the user. If matched, the user will be
              redirected to the contact list
        """
        # Check dialer setting limit
        if request.user and request.method == 'POST':
            # check Max Number of subscribers per campaign
            if check_dialer_setting(request, check_for="contact"):
                msg = _("you have too many contacts. you are allowed a maximum of %(limit)s")\
                    % {'limit': dialer_setting_limit(request, limit_for="contact")}
                messages.error(request, msg)

                # campaign limit reached
                frontend_send_notification(
                    request, NOTIFICATION_NAME.campaign_limit_reached)
                return HttpResponseRedirect(
                    reverse("admin:dialer_campaign_contact_changelist"))

        ctx = {}
        return super(ContactAdmin, self).add_view(request, extra_context=ctx)
Пример #4
0
def campaign_add(request):
    """Add a new campaign for the logged in user

    **Attributes**:

        * ``form`` - CampaignForm
        * ``template`` - frontend/campaign/change.html

    **Logic Description**:

        * Before adding a campaign, check dialer setting limit if
          applicable to the user.
        * Add the new campaign which will belong to the logged in user
          via CampaignForm & get redirected to campaign list
    """
    # If dialer setting is not attached with user, redirect to campaign list
    if not user_dialer_setting(request.user):
        request.session['error_msg'] = \
            _("in order to add a campaign, you need to have your settings configured properly, please contact the admin.")
        return HttpResponseRedirect("/campaign/")

    # Check dialer setting limit
    if request.user and request.method != 'POST':
        # check Max Number of running campaign
        if check_dialer_setting(request, check_for="campaign"):
            msg = _("you have too many campaigns. Max allowed %(limit)s") \
                % {'limit': dialer_setting_limit(request, limit_for="campaign")}
            request.session['msg'] = msg

            # campaign limit reached
            frontend_send_notification(request, NOTIFICATION_NAME.campaign_limit_reached)
            return HttpResponseRedirect("/campaign/")

    form = CampaignForm(request.user)
    # Add campaign
    if request.method == 'POST':
        form = CampaignForm(request.user, request.POST)
        if form.is_valid():
            obj = form.save(commit=False)
            contenttype = get_content_type(form.cleaned_data['content_object'])
            obj.content_type = contenttype['object_type']
            obj.object_id = contenttype['object_id']
            obj.user = request.user
            obj.save()

            form.save_m2m()

            request.session["msg"] = _('"%(name)s" added.') %\
                {'name': request.POST['name']}
            return HttpResponseRedirect('/campaign/')

    template = 'frontend/campaign/change.html'
    data = {
        'module': current_view(request),
        'form': form,
        'action': 'add',
        'AMD': settings.AMD,
    }
    return render_to_response(template, data,
                              context_instance=RequestContext(request))
Пример #5
0
def sms_campaign_add(request):
    """Add a new sms campaign for the logged in user

    **Attributes**:

        * ``form`` - SMSCampaignForm
        * ``template`` - frontend/sms_campaign/change.html

    **Logic Description**:

        * Before adding a sms campaign, check dialer setting limit if
          applicable to the user.
        * Add the new sms campaign which will belong to the logged in user
          via SMSCampaignForm & get redirected to sms campaign list
    """
    # If dialer setting is not attached with user, redirect to sms campaign list
    if not user_dialer_setting(request.user):
        request.session['error_msg'] = \
            _("in order to add a sms campaign, you need to have your \
               settings configured properly, please contact the admin.")
        return HttpResponseRedirect(redirect_url_to_smscampaign_list)

    # Check dialer setting limit
    if request.user and request.method != 'POST':
        # check Max Number of running campaign
        if check_sms_dialer_setting(request, check_for="smscampaign"):
            msg = _("you have too many sms campaigns. Max allowed %(limit)s")\
                % {'limit': dialer_setting_limit(request, limit_for="smscampaign")}
            request.session['msg'] = msg

            # sms campaign limit reached
            frontend_send_notification(
                request, SMS_NOTIFICATION_NAME.sms_campaign_limit_reached)
            return HttpResponseRedirect(redirect_url_to_smscampaign_list)

    form = SMSCampaignForm(request.user)
    # Add sms campaign
    if request.method == 'POST':
        form = SMSCampaignForm(request.user, request.POST)
        if form.is_valid():
            obj = form.save(commit=False)
            obj.user = User.objects.get(username=request.user)
            obj.save()
            form.save_m2m()

            request.session["msg"] = _('"%(name)s" is added.') %\
                {'name': request.POST['name']}
            return HttpResponseRedirect(redirect_url_to_smscampaign_list)

    template = 'frontend/sms_campaign/change.html'
    data = {
        'form': form,
        'action': 'add',
        'dialer_setting_msg': user_dialer_setting_msg(request.user),
    }
    return render_to_response(
        template, data, context_instance=RequestContext(request))
    def validate(self, attrs):
        """
        Validate campaign form
        """
        request = self.context['request']

        if request.method == 'POST':
            name_count = Campaign.objects.filter(name=attrs.get('name'),
                user=request.user).count()
            if name_count != 0:
                raise serializers.ValidationError("The Campaign name duplicated!")

        if not user_dialer_setting(request.user):
            raise serializers.ValidationError("Your system settings are not configured properly.")

        if check_dialer_setting(request, check_for="campaign"):
            raise serializers.ValidationError("Too many campaigns. Max allowed %s"
                    % dialer_setting_limit(request, limit_for="campaign"))

        frequency = attrs.get('frequency')
        if frequency:
            if check_dialer_setting(request, check_for="frequency", field_value=int(frequency)):
                raise serializers.ValidationError("Frequency limit of %s exceeded."
                    % dialer_setting_limit(request, limit_for="frequency"))

        callmaxduration = attrs.get('callmaxduration')
        if callmaxduration:
            if check_dialer_setting(request, check_for="duration", field_value=int(callmaxduration)):
                raise serializers.ValidationError("Duration limit of %s exceeded."
                    % dialer_setting_limit(request, limit_for="duration"))

        maxretry = attrs.get('maxretry')
        if maxretry:
            if check_dialer_setting(request, check_for="retry", field_value=int(maxretry)):
                raise serializers.ValidationError("Retries limit of %s exceeded."
                    % dialer_setting_limit(request, limit_for="retry"))

        calltimeout = attrs.get('calltimeout')
        if calltimeout:
            if check_dialer_setting(request, check_for="timeout", field_value=int(calltimeout)):
                raise serializers.ValidationError("Timeout limit of %s exceeded."
                    % dialer_setting_limit(request, limit_for="timeout"))

        return attrs
Пример #7
0
    def validate(self, attrs):
        """
        Validate campaign form
        """
        request = self.context['request']

        if request.method == 'POST':
            name_count = Campaign.objects.filter(name=attrs.get('name'),
                                                 user=request.user).count()
            if name_count != 0:
                raise serializers.ValidationError("The Campaign name duplicated!")

        if not user_dialer_setting(request.user):
            raise serializers.ValidationError("Your system settings are not configured properly.")

        if check_dialer_setting(request, check_for="campaign"):
            raise serializers.ValidationError("Too many campaigns. Max allowed %s"
                                              % dialer_setting_limit(request, limit_for="campaign"))

        frequency = attrs.get('frequency')
        if frequency:
            if check_dialer_setting(request, check_for="frequency", field_value=int(frequency)):
                raise serializers.ValidationError("Frequency limit of %s exceeded."
                                                  % dialer_setting_limit(request, limit_for="frequency"))

        callmaxduration = attrs.get('callmaxduration')
        if callmaxduration:
            if check_dialer_setting(request, check_for="duration", field_value=int(callmaxduration)):
                raise serializers.ValidationError("Duration limit of %s exceeded."
                                                  % dialer_setting_limit(request, limit_for="duration"))

        maxretry = attrs.get('maxretry')
        if maxretry:
            if check_dialer_setting(request, check_for="retry", field_value=int(maxretry)):
                raise serializers.ValidationError("Retries limit of %s exceeded."
                                                  % dialer_setting_limit(request, limit_for="retry"))

        calltimeout = attrs.get('calltimeout')
        if calltimeout:
            if check_dialer_setting(request, check_for="timeout", field_value=int(calltimeout)):
                raise serializers.ValidationError("Timeout limit of %s exceeded."
                                                  % dialer_setting_limit(request, limit_for="timeout"))

        return attrs
Пример #8
0
def contact_add(request):
    """Add a new contact into the selected phonebook for the logged in user

    **Attributes**:

        * ``form`` - ContactForm
        * ``template`` - frontend/contact/change.html

    **Logic Description**:

        * Before adding a contact, check dialer setting limit if applicable
          to the user.
        * Add new contact belonging to the logged in user
          via ContactForm & get redirected to the contact list
    """
    # Check dialer setting limit
    if request.user and request.method == 'POST':
        # check  Max Number of subscriber per campaign
        if check_dialer_setting(request, check_for="contact"):
            request.session['msg'] = \
                _("you have too many contacts per campaign. you are allowed a maximum of %(limit)s") % \
                {'limit': dialer_setting_limit(request, limit_for="contact")}

            # contact limit reached
            frontend_send_notification(request,
                                       NOTIFICATION_NAME.contact_limit_reached)
            return HttpResponseRedirect("/contact/")

    form = ContactForm(request.user)
    error_msg = False
    # Add contact
    if request.method == 'POST':
        form = ContactForm(request.user, request.POST)
        if form.is_valid():
            form.save()
            request.session["msg"] = _(
                '"%s" is added.') % request.POST['contact']
            return HttpResponseRedirect('/contact/')
        else:
            if len(request.POST['contact']) > 0:
                error_msg = _(
                    '"%s" cannot be added.') % request.POST['contact']

    phonebook_count = Phonebook.objects.filter(user=request.user).count()
    template = 'frontend/contact/change.html'
    data = {
        'module': current_view(request),
        'form': form,
        'action': 'add',
        'error_msg': error_msg,
        'phonebook_count': phonebook_count,
        'dialer_setting_msg': user_dialer_setting_msg(request.user),
    }
    return render_to_response(template,
                              data,
                              context_instance=RequestContext(request))
Пример #9
0
def sms_campaign_add(request):
    """Add a new sms campaign for the logged in user

    **Attributes**:

        * ``form`` - SMSCampaignForm
        * ``template`` - mod_sms/change.html

    **Logic Description**:

        * Before adding a sms campaign, check dialer setting limit if
          applicable to the user.
        * Add the new sms campaign which will belong to the logged in user
          via SMSCampaignForm & get redirected to sms campaign list
    """
    # If dialer setting is not attached with user, redirect to sms campaign list
    if not user_dialer_setting(request.user):
        request.session['error_msg'] = \
            _("in order to add a sms campaign, you need to have your \
               settings configured properly, please contact the admin."                                                                       )
        return HttpResponseRedirect(redirect_url_to_smscampaign_list)

    # Check dialer setting limit
    if request.user and request.method != 'POST':
        # check Max Number of running campaign
        if check_sms_dialer_setting(request, check_for="smscampaign"):
            msg = _("you have too many sms campaigns. Max allowed %(limit)s")\
                % {'limit': dialer_setting_limit(request, limit_for="smscampaign")}
            request.session['msg'] = msg

            # sms campaign limit reached
            frontend_send_notification(
                request, SMS_NOTIFICATION_NAME.sms_campaign_limit_reached)
            return HttpResponseRedirect(redirect_url_to_smscampaign_list)

    form = SMSCampaignForm(request.user, request.POST or None)
    # Add sms campaign
    if form.is_valid():
        obj = form.save(commit=False)
        obj.user = User.objects.get(username=request.user)
        obj.stoppeddate = obj.expirationdate
        obj.save()
        form.save_m2m()
        request.session["msg"] = _('"%(name)s" is added.') % {
            'name': request.POST['name']
        }
        return HttpResponseRedirect(redirect_url_to_smscampaign_list)

    data = {
        'form': form,
        'action': 'add',
    }
    return render_to_response('mod_sms/change.html',
                              data,
                              context_instance=RequestContext(request))
Пример #10
0
def contact_add(request):
    """Add a new contact into the selected phonebook for the logged in user

    **Attributes**:

        * ``form`` - ContactForm
        * ``template`` - frontend/contact/change.html

    **Logic Description**:

        * Before adding a contact, check dialer setting limit if applicable
          to the user.
        * Add new contact belonging to the logged in user
          via ContactForm & get redirected to the contact list
    """
    # Check dialer setting limit
    if request.user and request.method == 'POST':
        # check  Max Number of subscriber per campaign
        if check_dialer_setting(request, check_for="contact"):
            request.session['msg'] = \
                _("you have too many contacts per campaign. you are allowed a maximum of %(limit)s") % \
                {'limit': dialer_setting_limit(request, limit_for="contact")}

            # contact limit reached
            frontend_send_notification(request, NOTIFICATION_NAME.contact_limit_reached)
            return HttpResponseRedirect("/contact/")

    form = ContactForm(request.user)
    error_msg = False
    # Add contact
    if request.method == 'POST':
        form = ContactForm(request.user, request.POST)
        if form.is_valid():
            form.save()
            request.session["msg"] = _('"%(name)s" added.') %\
                {'name': request.POST['contact']}
            return HttpResponseRedirect('/contact/')
        else:
            if len(request.POST['contact']) > 0:
                error_msg = _('"%(name)s" cannot be added.') %\
                    {'name': request.POST['contact']}

    phonebook_count = Phonebook.objects.filter(user=request.user).count()
    template = 'frontend/contact/change.html'
    data = {
        'module': current_view(request),
        'form': form,
        'action': 'add',
        'error_msg': error_msg,
        'phonebook_count': phonebook_count,
        'dialer_setting_msg': user_dialer_setting_msg(request.user),
    }
    return render_to_response(template, data,
                              context_instance=RequestContext(request))
Пример #11
0
    def post(self, request):
        """
        create contacts in bulk
        """
        error = {}
        if request.method == 'POST':
            if not request.DATA:
                error['error'] = 'Data set is empty'

            if check_dialer_setting(request, check_for="contact"):
                error['error'] = "You have too many contacts per campaign. You are allowed a maximum of %s" % \
                    dialer_setting_limit(request, limit_for="contact")

            phonebook_id = request.DATA.get('phonebook_id')
            if phonebook_id and phonebook_id != '':
                try:
                    Phonebook.objects.get(id=phonebook_id, user=request.user)
                except Phonebook.DoesNotExist:
                    error['error'] = 'Phonebook is not valid!'
            else:
                error['error'] = 'Phonebook is not selected!'

        if error:
            return Response(error)

        phoneno_list = request.DATA.get('phoneno_list')
        phonebook_id = request.DATA.get('phonebook_id')
        phonenolist = list(phoneno_list.split(","))

        obj_phonebook = Phonebook.objects.get(id=phonebook_id,
                                              user=request.user)
        new_contact_count = 0
        for phoneno in phonenolist:
            # check phoneno in Contact
            dup_count = Contact.objects.filter(
                contact=phoneno, phonebook__user=request.user).count()

            # If dup_count is zero, create new contact
            if dup_count == 0:
                new_contact = Contact.objects.create(
                    phonebook=obj_phonebook,
                    contact=phoneno,
                )
                new_contact_count = new_contact_count + 1
                new_contact.save()
            else:
                error_msg = "The contact duplicated (%s)!\n" % phoneno
                return Response({'error': error_msg})

        return Response({'result': 'Bulk contacts are created'})
Пример #12
0
def contact_add(request):
    """Add a new contact into the selected phonebook for the logged in user

    **Attributes**:

        * ``form`` - ContactForm
        * ``template`` - frontend/contact/change.html

    **Logic Description**:

        * Before adding a contact, check dialer setting limit if applicable
          to the user.
        * Add new contact belonging to the logged in user
          via ContactForm & get redirected to the contact list
    """
    # Check dialer setting limit
    if request.user and request.method == "POST":
        if check_dialer_setting(request, check_for="contact"):
            request.session["msg"] = _("you have too many contacts. you are allowed a maximum of %(limit)s") % {
                "limit": dialer_setting_limit(request, limit_for="contact")
            }

            # contact limit reached
            frontend_send_notification(request, NOTIFICATION_NAME.contact_limit_reached)
            return HttpResponseRedirect("/contact/")

    form = ContactForm(request.user)
    error_msg = False
    # Add contact
    if request.method == "POST":
        form = ContactForm(request.user, request.POST)
        if form.is_valid():
            form.save()
            request.session["msg"] = _('"%s" is added.') % request.POST["contact"]
            return HttpResponseRedirect("/contact/")
        else:
            if len(request.POST["contact"]) > 0:
                error_msg = _('"%s" cannot be added.') % request.POST["contact"]

    phonebook_count = Phonebook.objects.filter(user=request.user).count()
    template = "frontend/contact/change.html"
    data = {
        "form": form,
        "action": "add",
        "error_msg": error_msg,
        "phonebook_count": phonebook_count,
        "dialer_setting_msg": user_dialer_setting_msg(request.user),
    }
    return render_to_response(template, data, context_instance=RequestContext(request))
Пример #13
0
    def post(self, request):
        """
        create contacts in bulk
        """
        error = {}
        if request.method == 'POST':
            if not request.DATA:
                error['error'] = 'Data set is empty'

            if check_dialer_setting(request, check_for="contact"):
                error['error'] = "You have too many contacts per campaign. You are allowed a maximum of %s" % \
                    dialer_setting_limit(request, limit_for="contact")

            phonebook_id = request.DATA.get('phonebook_id')
            if phonebook_id and phonebook_id != '':
                try:
                    Phonebook.objects.get(id=phonebook_id, user=request.user)
                except Phonebook.DoesNotExist:
                    error['error'] = 'Phonebook is not valid!'
            else:
                error['error'] = 'Phonebook is not selected!'

        if error:
            return Response(error)

        phoneno_list = request.DATA.get('phoneno_list')
        phonebook_id = request.DATA.get('phonebook_id')
        phonenolist = list(phoneno_list.split(","))

        obj_phonebook = Phonebook.objects.get(id=phonebook_id, user=request.user)
        new_contact_count = 0
        for phoneno in phonenolist:
            # check phoneno in Contact
            dup_count = Contact.objects.filter(contact=phoneno, phonebook__user=request.user).count()

            # If dup_count is zero, create new contact
            if dup_count == 0:
                new_contact = Contact.objects.create(
                    phonebook=obj_phonebook,
                    contact=phoneno,
                )
                new_contact_count = new_contact_count + 1
                new_contact.save()
            else:
                error_msg = "The contact duplicated (%s)!\n" % phoneno
                return Response({'error': error_msg})

        return Response({'result': 'Bulk contacts are created'})
Пример #14
0
    def is_valid(self, bundle, request=None):
        errors = {}
        if not bundle.data:
            errors['Data'] = ['Data set is empty']

        if check_dialer_setting(request, check_for="contact"):
            errors['contact_dialer_setting'] = ["You have too many contacts per campaign. You are allowed a maximum of %s" %
                        dialer_setting_limit(request, limit_for="contact")]
        if request.method == 'POST':
            phonebook_id = bundle.data.get('phonebook_id')
            if phonebook_id:
                try:
                    Phonebook.objects.get(id=phonebook_id)
                except Phonebook.DoesNotExist:
                    errors['phonebook_error'] = ["Phonebook is not selected!"]
            else:
                errors['phonebook_error'] = ["Phonebook is not selected!"]
        return errors
Пример #15
0
    def is_valid(self, bundle, request=None):
        errors = {}

        if not bundle.data:
            errors['Data'] = ['Data set is empty']
        if check_dialer_setting(request, check_for="contact"):
            errors['contact_dialer_setting'] = ["You have too many contacts \
                per campaign. You are allowed a maximum of %s"                                                               %\
                            dialer_setting_limit(request, limit_for="contact")]

        phonebook_id = bundle.data.get('phonebook_id')
        if phonebook_id:
            try:
                Phonebook.objects.get(id=phonebook_id)
            except Phonebook.DoesNotExist:
                errors['phonebook_error'] = ["Phonebook is not selected!"]
        else:
            errors['phonebook_error'] = ["Phonebook is not selected!"]

        return errors
Пример #16
0
    def add_view(self, request, extra_context=None):
        """
        Override django add_view method for checking the dialer setting limit

        **Logic Description**:

            * Before adding campaign, check dialer setting limit if applicable
              to the user, if matched then the user will be redirected to
              the campaign list
        """
        # Check dialer setting limit
        # check Max Number of running campaigns
        if check_dialer_setting(request, check_for="campaign"):
            msg = _("you have too many campaigns. max allowed %(limit)s") % \
                {'limit': dialer_setting_limit(request, limit_for="campaign")}
            messages.error(request, msg)

            return HttpResponseRedirect(reverse("admin:dialer_campaign_campaign_changelist"))
        ctx = {}
        return super(CampaignAdmin, self).add_view(request, extra_context=ctx)
Пример #17
0
    def add_view(self, request, extra_context=None):
        """
        Override django add_view method for checking the dialer setting limit

        **Logic Description**:

            * Before adding campaign, check dialer setting limit if applicable
              to the user, if matched then the user will be redirected to
              the campaign list
        """
        # Check dialer setting limit
        # check Max Number of running campaigns
        if check_dialer_setting(request, check_for="campaign"):
            msg = _("you have too many campaigns. max allowed %(limit)s") % \
                {'limit': dialer_setting_limit(request, limit_for="campaign")}
            messages.error(request, msg)

            return HttpResponseRedirect(reverse("admin:dialer_campaign_campaign_changelist"))
        ctx = {}
        return super(CampaignAdmin, self).add_view(request, extra_context=ctx)
Пример #18
0
def contact_add(request):
    """Add a new contact into the selected phonebook for the logged in user

    **Attributes**:

        * ``form`` - ContactForm
        * ``template`` - dialer_contact/contact/change.html

    **Logic Description**:

        * Before adding a contact, check dialer setting limit if applicable
          to the user.
        * Add new contact belonging to the logged in user
          via ContactForm & get redirected to the contact list
    """
    # Check dialer setting limit
    if request.user and request.method == 'POST':
        if check_dialer_setting(request, check_for="contact"):
            request.session['msg'] = _("you have too many contacts. you are allowed a maximum of %(limit)s") % \
                {'limit': dialer_setting_limit(request, limit_for="contact")}

            # contact limit reached
            frontend_send_notification(request,
                                       NOTIFICATION_NAME.contact_limit_reached)
            return HttpResponseRedirect(redirect_url_to_contact_list)

    form = ContactForm(request.user, request.POST or None)
    # Add contact
    if form.is_valid():
        form.save()
        request.session["msg"] = _('"%s" is added.') % request.POST['contact']
        return HttpResponseRedirect(redirect_url_to_contact_list)

    data = {
        'form': form,
        'action': 'add',
    }
    return render_to_response('dialer_contact/contact/change.html',
                              data,
                              context_instance=RequestContext(request))
Пример #19
0
def contact_add(request):
    """Add a new contact into the selected phonebook for the logged in user

    **Attributes**:

        * ``form`` - ContactForm
        * ``template`` - dialer_contact/contact/change.html

    **Logic Description**:

        * Before adding a contact, check dialer setting limit if applicable
          to the user.
        * Add new contact belonging to the logged in user
          via ContactForm & get redirected to the contact list
    """
    # Check dialer setting limit
    if request.user and request.method == 'POST':
        if check_dialer_setting(request, check_for="contact"):
            request.session['msg'] = _("you have too many contacts. you are allowed a maximum of %(limit)s") % \
                {'limit': dialer_setting_limit(request, limit_for="contact")}

            # contact limit reached
            frontend_send_notification(request, NOTIFICATION_NAME.contact_limit_reached)
            return HttpResponseRedirect(redirect_url_to_contact_list)

    form = ContactForm(request.user, request.POST or None)
    # Add contact
    if form.is_valid():
        form.save()
        request.session["msg"] = _('"%s" is added.') % request.POST['contact']
        return HttpResponseRedirect(redirect_url_to_contact_list)

    data = {
        'form': form,
        'action': 'add',
    }
    return render_to_response('dialer_contact/contact/change.html', data, context_instance=RequestContext(request))
Пример #20
0
def contact_import(request):
    """Import CSV file of Contacts for the logged in user

    **Attributes**:

        * ``form`` - Contact_fileImport
        * ``template`` - dialer_contact/contact/import_contact.html

    **Logic Description**:

        * Before adding contacts, check dialer setting limit if applicable
          to the user.
        * Add new contacts which will belong to the logged in user
          via csv file & get the result (upload success and failure
          statistics)

    **Important variable**:

        * total_rows - Total no. of records in the CSV file
        * retail_record_count - No. of records imported from the CSV file
    """
    # Check dialer setting limit
    if request.user and request.method == 'POST':
        # check  Max Number of contacts
        if check_dialer_setting(request, check_for="contact"):
            request.session['msg'] = _("you have too many contacts. you are allowed a maximum of %(limit)s") % \
                {'limit': dialer_setting_limit(request, limit_for="contact")}

            # contact limit reached
            frontend_send_notification(request,
                                       NOTIFICATION_NAME.contact_limit_reached)
            return HttpResponseRedirect(redirect_url_to_contact_list)

    form = Contact_fileImport(request.user, request.POST or None, request.FILES
                              or None)
    csv_data = ''
    msg = ''
    error_msg = ''
    success_import_list = []
    type_error_import_list = []
    contact_cnt = 0
    bulk_record = []

    if form.is_valid():
        # col_no - field name
        #  0     - contact
        #  1     - last_name
        #  2     - first_name
        #  3     - email
        #  4     - description
        #  5     - status
        #  6     - address
        #  7     - city
        #  8     - country
        #  9     - country
        # 10     - unit_number
        # 11     - additional_vars
        # To count total rows of CSV file
        records = csv.reader(request.FILES['csv_file'],
                             delimiter='|',
                             quotechar='"')
        total_rows = len(list(records))
        BULK_SIZE = 1000
        csv_data = csv.reader(request.FILES['csv_file'],
                              delimiter='|',
                              quotechar='"')
        #Get Phonebook Obj
        phonebook = get_object_or_404(Phonebook,
                                      pk=request.POST['phonebook'],
                                      user=request.user)
        #Read each Row
        for row in csv_data:
            row = striplist(row)
            if not row or str(row[0]) == 0:
                continue

            #Check field type
            if not int(row[5]):
                error_msg = _(
                    "invalid value for import! please check the import samples or phonebook is not valid"
                )
                type_error_import_list.append(row)
                break

            if len(row[9]) > 2:
                error_msg = _(
                    "invalid value for country code, it needs to be a valid ISO 3166-1 alpha-2 codes"
                )
                type_error_import_list.append(row)
                break

            row_11 = ''
            if row[11]:
                try:
                    row_11 = json.loads(row[11])
                except:
                    row_11 = ''

            bulk_record.append(
                Contact(
                    phonebook=phonebook,
                    contact=row[0],
                    last_name=row[1],
                    first_name=row[2],
                    email=row[3],
                    description=row[4],
                    status=int(row[5]),
                    address=row[6],
                    city=row[7],
                    state=row[8],
                    country=row[
                        9],  # Note: country needs to be a country code (CA, ES)
                    unit_number=row[10],
                    additional_vars=row_11))

            contact_cnt = contact_cnt + 1

            if contact_cnt < 100:
                #We want to display only 100 lines of the success import
                success_import_list.append(row)

            if contact_cnt % BULK_SIZE == 0:
                #Bulk insert
                Contact.objects.bulk_create(bulk_record)
                bulk_record = []

        # remaining record
        Contact.objects.bulk_create(bulk_record)
        bulk_record = []

    #check if there is contact imported
    if contact_cnt > 0:
        msg = _('%(contact_cnt)s contact(s) have been uploaded successfully out of %(total_rows)s row(s)!') \
            % {'contact_cnt': contact_cnt, 'total_rows': total_rows}

    data = RequestContext(
        request, {
            'form': form,
            'csv_data': csv_data,
            'msg': msg,
            'error_msg': error_msg,
            'success_import_list': success_import_list,
            'type_error_import_list': type_error_import_list,
        })
    return render_to_response('dialer_contact/contact/import_contact.html',
                              data,
                              context_instance=RequestContext(request))
Пример #21
0
    def is_valid(self, bundle, request=None):
        errors = {}

        if not bundle.data:
            return {'__all__': 'Please enter data'}
        startingdate = bundle.data.get('startingdate')
        expirationdate = bundle.data.get('expirationdate')

        if bundle.request.method == 'POST':
            startingdate = get_value_if_none(startingdate, time.time())
            # expires in 90 days
            expirationdate = get_value_if_none(expirationdate,
                time.time() + 86400 * 90)
            #Startdate and expirationdate are UTC -> convert to localtime
            startingdate = float(startingdate) - time.altzone
            expirationdate = float(expirationdate) - time.altzone

            bundle.data['startingdate'] = time.strftime('%Y-%m-%d %H:%M:%S',
                time.gmtime(startingdate))
            bundle.data['expirationdate'] = time.strftime('%Y-%m-%d %H:%M:%S',
                time.gmtime(expirationdate))

        if bundle.request.method == 'PUT':
            if startingdate:
                bundle.data['startingdate'] = time.strftime(
                    '%Y-%m-%d %H:%M:%S', time.gmtime(float(startingdate)))
            if expirationdate:
                bundle.data['expirationdate'] = time.strftime(
                    '%Y-%m-%d %H:%M:%S', time.gmtime(float(expirationdate)))

        if not user_dialer_setting(bundle.request.user):
            errors['user_dialer_setting'] = ['Your settings are not configured properly, Please contact the administrator.']

        if check_dialer_setting(request, check_for="campaign"):
            errors['chk_campaign'] = ["Too many campaigns. Max allowed %s"
                % dialer_setting_limit(bundle.request, limit_for="campaign")]

        frequency = bundle.data.get('frequency')
        if frequency:
            if check_dialer_setting(bundle.request, check_for="frequency", field_value=int(frequency)):
                errors['chk_frequency'] = ["Frequency limit of %s exceeded."
                    % dialer_setting_limit(request, limit_for="frequency")]

        callmaxduration = bundle.data.get('callmaxduration')
        if callmaxduration:
            if check_dialer_setting(bundle.request, check_for="duration", field_value=int(callmaxduration)):
                errors['chk_duration'] = ["Duration limit of %s exceeded."
                    % dialer_setting_limit(bundle.request, limit_for="duration")]

        maxretry = bundle.data.get('maxretry')
        if maxretry:
            if check_dialer_setting(bundle.request, check_for="retry", field_value=int(maxretry)):
                errors['chk_duration'] = ["Retries limit of %s exceeded."
                    % dialer_setting_limit(bundle.request, limit_for="retry")]

        calltimeout = bundle.data.get('calltimeout')
        if calltimeout:
            if check_dialer_setting(request, check_for="timeout", field_value=int(calltimeout)):
                errors['chk_timeout'] = ["Timeout limit of %s exceeded."
                    % dialer_setting_limit(request, limit_for="timeout")]

        aleg_gateway_id = bundle.data.get('aleg_gateway')
        if aleg_gateway_id:
            try:
                Gateway.objects.get(id=aleg_gateway_id)
                bundle.data['aleg_gateway'] = '/api/v1/gateway/%s/' % aleg_gateway_id
            except:
                errors['chk_gateway'] = ["The Gateway ID doesn't exist!"]

        content_type = bundle.data.get('content_type')
        if content_type == 'survey_template':
            try:
                content_type_id = ContentType.objects.get(model=str(content_type)).id
                bundle.data['content_type'] = '/api/v1/contenttype/%s/' % content_type_id
            except:
                errors['chk_content_type'] = ["The ContentType doesn't exist!"]
        else:
            errors['chk_content_type'] = ["Entered wrong option. Please enter 'survey_template' !"]

        object_id = bundle.data.get('object_id')
        if object_id:
            try:
                bundle.data['object_id'] = int(object_id)
            except:
                errors['chk_object_id'] = ["object_id must be digit"]
        else:
            errors['chk_object_id'] = ["App Object ID doesn't exist!"]


        if bundle.request.method == 'POST':
            name_count = Campaign.objects.filter(name=bundle.data.get('name'),
                user=bundle.request.user).count()
            if (name_count != 0):
                errors['chk_campaign_name'] = ["The Campaign name duplicated!"]

        # Voicemail setting is not enabled by default
        if settings.AMD:
            voicemail = bundle.data.get('voicemail')
            if voicemail:
                bundle.data['voicemail'] = voicemail
                amd_behavior = bundle.data.get('amd_behavior')
                audiofile_id = bundle.data.get('voicemail_audiofile')
                if audiofile_id:
                    try:
                        AudioFile.objects.get(id=audiofile_id)
                        bundle.data['voicemail_audiofile'] = '/api/v1/audiofile/%s/' % audiofile_id
                    except:
                        errors['voicemail_audiofile'] = ["The audiofile ID doesn't exist!"]
            else:
                errors['voicemail'] = ["voicemail not enabled!"]

        if errors:
            raise BadRequest(errors)
        return errors
Пример #22
0
def campaign_add(request):
    """Add a new campaign for the logged in user

    **Attributes**:

        * ``form`` - CampaignForm
        * ``template`` - frontend/campaign/change.html

    **Logic Description**:

        * Before adding a campaign, check dialer setting limit if
          applicable to the user.
        * Add the new campaign which will belong to the logged in user
          via CampaignForm & get redirected to campaign list
    """
    # If dialer setting is not attached with user, redirect to campaign list
    if not user_dialer_setting(request.user):
        request.session['error_msg'] = \
            _("in order to add a campaign, you need to have your settings configured properly, please contact the admin.")
        return HttpResponseRedirect("/campaign/")

    # Check dialer setting limit
    if request.user and request.method != 'POST':
        # check Max Number of running campaign
        if check_dialer_setting(request, check_for="campaign"):
            msg = _("you have too many campaigns. Max allowed %(limit)s") \
                % {'limit': dialer_setting_limit(request, limit_for="campaign")}
            request.session['msg'] = msg

            # campaign limit reached
            frontend_send_notification(
                request, NOTIFICATION_NAME.campaign_limit_reached)
            return HttpResponseRedirect("/campaign/")

    form = CampaignForm(request.user)
    # Add campaign
    if request.method == 'POST':
        form = CampaignForm(request.user, request.POST)
        if form.is_valid():
            obj = form.save(commit=False)
            contenttype = get_content_type(form.cleaned_data['content_object'])
            obj.content_type = contenttype['object_type']
            obj.object_id = contenttype['object_id']
            obj.user = request.user
            obj.save()

            form.save_m2m()

            request.session["msg"] = _('"%(name)s" added.') %\
                {'name': request.POST['name']}
            return HttpResponseRedirect('/campaign/')

    template = 'frontend/campaign/change.html'
    data = {
        'module': current_view(request),
        'form': form,
        'action': 'add',
        'AMD': settings.AMD,
    }
    return render_to_response(template,
                              data,
                              context_instance=RequestContext(request))
Пример #23
0
    def import_contact(self, request):
        """Add custom method in django admin view to import CSV file of
        Contacts

        **Attributes**:

            * ``form`` - Contact_fileImport
            * ``template`` - admin/dialer_campaign/contact/import_contact.html

        **Logic Description**:

            * Before adding contact, check the dialer setting limit if
              applicable to the user.
            * Add a new contact which will belong to the logged in user
              via csv file & get the result (Upload success & failure
              statistics)

        **Important variable**:

            * total_rows - Total no. of records in the CSV file
            * retail_record_count - No. of records which are imported from
              The CSV file
        """
        # Check dialer setting limit
        if request.user and request.method == 'POST':
            # check Max Number of subscribers per campaign
            if check_dialer_setting(request, check_for="contact"):
                msg = _("you have too many contacts per campaign. you are allowed a maximum of %(limit)s")\
                    % {'limit': dialer_setting_limit(request, limit_for="contact")}
                messages.error(request, msg)

                # campaign limit reached
                frontend_send_notification(request, NOTIFICATION_NAME.campaign_limit_reached)
                return HttpResponseRedirect(reverse(
                    "admin:dialer_campaign_contact_changelist"))

        opts = Contact._meta
        rdr = ''  # will contain CSV data
        msg = ''
        error_msg = ''
        success_import_list = []
        type_error_import_list = []
        contact_cnt = 0
        bulk_record = []
        if request.method == 'POST':
            form = Contact_fileImport(
                request.user, request.POST, request.FILES)
            if form.is_valid():
                # col_no - field name
                #  0     - contact
                #  1     - last_name
                #  2     - first_name
                #  3     - email
                #  4     - description
                #  5     - status
                #  6     - address
                #  7     - city
                #  8     - state
                #  9     - country
                # 10     - unit_number
                # 11     - additional_vars
                # To count total rows of CSV file
                records = csv.reader(
                    request.FILES['csv_file'], delimiter='|', quotechar='"')
                total_rows = len(list(records))
                BULK_SIZE = 1000
                rdr = csv.reader(
                    request.FILES['csv_file'], delimiter='|', quotechar='"')

                #Get Phonebook Obj
                phonebook = Phonebook.objects.get(pk=request.POST['phonebook'])

                contact_cnt = 0
                # Read each Row
                for row in rdr:
                    row = striplist(row)
                    if not row or str(row[0]) == 0:
                        continue

                    # check field type
                    if not int(row[5]):
                        error_msg = _("invalid value for import! please check the import samples or phonebook is not valid")
                        type_error_import_list.append(row)
                        break

                    row_11 = ''
                    if row[11]:
                        row_11 = json.loads(row[11])

                    bulk_record.append(
                        Contact(
                            phonebook=phonebook,
                            contact=row[0],
                            last_name=row[1],
                            first_name=row[2],
                            email=row[3],
                            description=row[4],
                            status=int(row[5]),
                            address=row[6],
                            city=row[7],
                            state=row[8],
                            country=row[9],
                            unit_number=row[10],
                            additional_vars=row_11)
                    )

                    contact_cnt = contact_cnt + 1
                    if contact_cnt < 100:
                        success_import_list.append(row)

                    if contact_cnt % BULK_SIZE == 0:
                        # Bulk insert
                        Contact.objects.bulk_create(bulk_record)
                        bulk_record = []

                # remaining record
                Contact.objects.bulk_create(bulk_record)
                bulk_record = []

                #check if there is contact imported
                if contact_cnt > 0:
                    msg = _('%(contact_cnt)s contact(s) are uploaded successfully out of %(total_rows)s row(s) !!')\
                        % {'contact_cnt': contact_cnt, 'total_rows': total_rows}
        else:
            form = Contact_fileImport(request.user)

        ctx = RequestContext(request, {
            'form': form,
            'opts': opts,
            'model_name': opts.object_name.lower(),
            'app_label': _('dialer contact'),
            'title': _('import contact'),
            'rdr': rdr,
            'msg': msg,
            'error_msg': error_msg,
            'success_import_list': success_import_list,
            'type_error_import_list': type_error_import_list,
        })
        return render_to_response(
            'admin/dialer_contact/contact/import_contact.html',
            context_instance=ctx)
Пример #24
0
    def import_contact(self, request):
        """Add custom method in django admin view to import CSV file of
        Contacts

        **Attributes**:

            * ``form`` - Contact_fileImport
            * ``template`` - admin/dialer_campaign/contact/import_contact.html

        **Logic Description**:

            * Before adding contact, check the dialer setting limit if
              applicable to the user.
            * Add a new contact which will belong to the logged in user
              via csv file & get the result (Upload success & failure
              statistics)

        **Important variable**:

            * total_rows - Total no. of records in the CSV file
            * retail_record_count - No. of records which are imported from
              The CSV file
        """
        # Check dialer setting limit
        if request.user and request.method == 'POST':
            # check Max Number of subscribers per campaign
            if check_dialer_setting(request, check_for="contact"):
                msg = _("you have too many contacts. you are allowed a maximum of %(limit)s")\
                    % {'limit': dialer_setting_limit(request, limit_for="contact")}
                messages.error(request, msg)

                # campaign limit reached
                frontend_send_notification(
                    request, NOTIFICATION_NAME.campaign_limit_reached)
                return HttpResponseRedirect(
                    reverse("admin:dialer_campaign_contact_changelist"))

        opts = Contact._meta
        rdr = ''  # will contain CSV data
        msg = ''
        error_msg = ''
        success_import_list = []
        type_error_import_list = []
        contact_cnt = 0
        bulk_record = []
        form = Contact_fileImport(request.user, request.POST or None,
                                  request.FILES or None)
        if form.is_valid():
            # col_no - field name
            #  0     - contact
            #  1     - last_name
            #  2     - first_name
            #  3     - email
            #  4     - description
            #  5     - status
            #  6     - address
            #  7     - city
            #  8     - state
            #  9     - country
            # 10     - unit_number
            # 11     - additional_vars
            # To count total rows of CSV file
            records = csv.reader(request.FILES['csv_file'],
                                 delimiter='|',
                                 quotechar='"')
            total_rows = len(list(records))
            BULK_SIZE = 1000
            rdr = csv.reader(request.FILES['csv_file'],
                             delimiter='|',
                             quotechar='"')

            #Get Phonebook Obj
            phonebook = Phonebook.objects.get(pk=request.POST['phonebook'])

            contact_cnt = 0
            # Read each Row
            for row in rdr:
                row = striplist(row)
                if not row or str(row[0]) == 0:
                    continue

                # check field type
                if not int(row[5]):
                    error_msg = _(
                        "invalid value for import! please check the import samples or phonebook is not valid"
                    )
                    type_error_import_list.append(row)
                    break

                if len(row[9]) > 2:
                    error_msg = _(
                        "invalid value for country code, it needs to be a valid ISO 3166-1 alpha-2 codes (http://en.wikipedia.org/wiki/ISO_3166-1)"
                    )
                    type_error_import_list.append(row)
                    break

                row_11 = ''
                if row[11]:
                    row_11 = json.loads(row[11])

                bulk_record.append(
                    Contact(phonebook=phonebook,
                            contact=row[0],
                            last_name=row[1],
                            first_name=row[2],
                            email=row[3],
                            description=row[4],
                            status=int(row[5]),
                            address=row[6],
                            city=row[7],
                            state=row[8],
                            country=row[9],
                            unit_number=row[10],
                            additional_vars=row_11))

                contact_cnt = contact_cnt + 1
                if contact_cnt < 100:
                    success_import_list.append(row)

                if contact_cnt % BULK_SIZE == 0:
                    # Bulk insert
                    Contact.objects.bulk_create(bulk_record)
                    bulk_record = []

            # remaining record
            Contact.objects.bulk_create(bulk_record)
            bulk_record = []

            #check if there is contact imported
            if contact_cnt > 0:
                msg = _('%(contact_cnt)s contact(s) have been uploaded successfully out of %(total_rows)s row(s)!')\
                    % {'contact_cnt': contact_cnt, 'total_rows': total_rows}

        ctx = RequestContext(
            request, {
                'form': form,
                'opts': opts,
                'model_name': opts.object_name.lower(),
                'app_label': _('dialer contact'),
                'title': _('import contact'),
                'rdr': rdr,
                'msg': msg,
                'error_msg': error_msg,
                'success_import_list': success_import_list,
                'type_error_import_list': type_error_import_list,
            })
        return render_to_response(
            'admin/dialer_contact/contact/import_contact.html',
            context_instance=ctx)
Пример #25
0
    def is_valid(self, bundle, request=None):
        errors = {}

        if not bundle.data:
            return {'__all__': 'Please enter data'}
        startingdate = bundle.data.get('startingdate')
        expirationdate = bundle.data.get('expirationdate')

        if bundle.request.method == 'POST':
            startingdate = get_value_if_none(startingdate, time.time())
            # expires in 90 days
            expirationdate = get_value_if_none(expirationdate,
                                               time.time() + 86400 * 90)
            #Startdate and expirationdate are UTC -> convert to localtime
            startingdate = float(startingdate) - time.altzone
            expirationdate = float(expirationdate) - time.altzone

            bundle.data['startingdate'] = time.strftime(
                '%Y-%m-%d %H:%M:%S', time.gmtime(startingdate))
            bundle.data['expirationdate'] = time.strftime(
                '%Y-%m-%d %H:%M:%S', time.gmtime(expirationdate))

        if bundle.request.method == 'PUT':
            if startingdate:
                bundle.data['startingdate'] = time.strftime(
                    '%Y-%m-%d %H:%M:%S', time.gmtime(float(startingdate)))
            if expirationdate:
                bundle.data['expirationdate'] = time.strftime(
                    '%Y-%m-%d %H:%M:%S', time.gmtime(float(expirationdate)))

        if not user_dialer_setting(bundle.request.user):
            errors['user_dialer_setting'] = [
                'Your settings are not configured properly, Please contact the administrator.'
            ]

        if check_dialer_setting(request, check_for="campaign"):
            errors['chk_campaign'] = [
                "Too many campaigns. Max allowed %s" %
                dialer_setting_limit(bundle.request, limit_for="campaign")
            ]

        frequency = bundle.data.get('frequency')
        if frequency:
            if check_dialer_setting(bundle.request,
                                    check_for="frequency",
                                    field_value=int(frequency)):
                errors['chk_frequency'] = [
                    "Frequency limit of %s exceeded." %
                    dialer_setting_limit(request, limit_for="frequency")
                ]

        callmaxduration = bundle.data.get('callmaxduration')
        if callmaxduration:
            if check_dialer_setting(bundle.request,
                                    check_for="duration",
                                    field_value=int(callmaxduration)):
                errors['chk_duration'] = [
                    "Duration limit of %s exceeded." %
                    dialer_setting_limit(bundle.request, limit_for="duration")
                ]

        maxretry = bundle.data.get('maxretry')
        if maxretry:
            if check_dialer_setting(bundle.request,
                                    check_for="retry",
                                    field_value=int(maxretry)):
                errors['chk_duration'] = [
                    "Retries limit of %s exceeded." %
                    dialer_setting_limit(bundle.request, limit_for="retry")
                ]

        calltimeout = bundle.data.get('calltimeout')
        if calltimeout:
            if check_dialer_setting(request,
                                    check_for="timeout",
                                    field_value=int(calltimeout)):
                errors['chk_timeout'] = [
                    "Timeout limit of %s exceeded." %
                    dialer_setting_limit(request, limit_for="timeout")
                ]

        aleg_gateway_id = bundle.data.get('aleg_gateway')
        if aleg_gateway_id:
            try:
                Gateway.objects.get(id=aleg_gateway_id)
                bundle.data[
                    'aleg_gateway'] = '/api/v1/gateway/%s/' % aleg_gateway_id
            except:
                errors['chk_gateway'] = ["The Gateway ID doesn't exist!"]

        content_type = bundle.data.get('content_type')
        if content_type == 'survey_template':
            try:
                content_type_id = ContentType.objects.get(
                    model=str(content_type)).id
                bundle.data[
                    'content_type'] = '/api/v1/contenttype/%s/' % content_type_id
            except:
                errors['chk_content_type'] = ["The ContentType doesn't exist!"]
        else:
            errors['chk_content_type'] = [
                "Entered wrong option. Please enter 'survey_template' !"
            ]

        object_id = bundle.data.get('object_id')
        if object_id:
            try:
                bundle.data['object_id'] = int(object_id)
            except:
                errors['chk_object_id'] = ["object_id must be digit"]
        else:
            errors['chk_object_id'] = ["App Object ID doesn't exist!"]

        if bundle.request.method == 'POST':
            name_count = Campaign.objects.filter(
                name=bundle.data.get('name'),
                user=bundle.request.user).count()
            if (name_count != 0):
                errors['chk_campaign_name'] = ["The Campaign name duplicated!"]

        # Voicemail setting is not enabled by default
        if settings.AMD:
            voicemail = bundle.data.get('voicemail')
            if voicemail:
                bundle.data['voicemail'] = voicemail
                amd_behavior = bundle.data.get('amd_behavior')
                audiofile_id = bundle.data.get('voicemail_audiofile')
                if audiofile_id:
                    try:
                        AudioFile.objects.get(id=audiofile_id)
                        bundle.data[
                            'voicemail_audiofile'] = '/api/v1/audiofile/%s/' % audiofile_id
                    except:
                        errors['voicemail_audiofile'] = [
                            "The audiofile ID doesn't exist!"
                        ]
            else:
                errors['voicemail'] = ["voicemail not enabled!"]

        if errors:
            raise BadRequest(errors)
        return errors
Пример #26
0
    def is_valid(self, bundle, request=None):
        errors = {}
        if not bundle.data:
            errors['Data'] = ['Data set is empty']
        startingdate = bundle.data.get('startingdate')
        expirationdate = bundle.data.get('expirationdate')

        if request.method == 'POST':
            startingdate = get_value_if_none(startingdate, time.time())
            # expires in 90 days
            expirationdate = get_value_if_none(expirationdate,
                                               time.time() + 86400 * 90)
            #Startdate and expirationdate are UTC -> convert to localtime
            startingdate = float(startingdate) - time.altzone
            expirationdate = float(expirationdate) - time.altzone

            bundle.data['startingdate'] = time.strftime(
                '%Y-%m-%d %H:%M:%S', time.gmtime(float(startingdate)))
            bundle.data['expirationdate'] = time.strftime(
                '%Y-%m-%d %H:%M:%S', time.gmtime(float(expirationdate)))

        if request.method == 'PUT':
            if startingdate:
                bundle.data['startingdate'] = time.strftime(
                    '%Y-%m-%d %H:%M:%S', time.gmtime(float(startingdate)))
            if expirationdate:
                bundle.data['expirationdate'] = time.strftime(
                    '%Y-%m-%d %H:%M:%S', time.gmtime(float(expirationdate)))

        if user_attached_with_dialer_settings(request):
            errors['user_dialer_setting'] = [
                'Your settings are not \
                    configured properly, Please contact the administrator.'
            ]

        if check_dialer_setting(request, check_for="campaign"):
            errors['chk_campaign'] = ["Too many campaigns. Max allowed %s"\
                    % dialer_setting_limit(request, limit_for="campaign")]

        frequency = bundle.data.get('frequency')
        if frequency:
            if check_dialer_setting(request,
                                    check_for="frequency",
                                    field_value=int(frequency)):
                errors['chk_frequency'] = ["Frequency limit of %s exceeded."\
                    % dialer_setting_limit(request, limit_for="frequency")]

        callmaxduration = bundle.data.get('callmaxduration')
        if callmaxduration:
            if check_dialer_setting(request,
                                    check_for="duration",
                                    field_value=int(callmaxduration)):
                errors['chk_duration'] = ["Duration limit of %s exceeded."\
                    % dialer_setting_limit(request, limit_for="duration")]

        maxretry = bundle.data.get('maxretry')
        if maxretry:
            if check_dialer_setting(request,
                                    check_for="retry",
                                    field_value=int(maxretry)):
                errors['chk_duration'] = ["Retries limit of %s exceeded."\
                    % dialer_setting_limit(request, limit_for="retry")]

        calltimeout = bundle.data.get('calltimeout')
        if calltimeout:
            if check_dialer_setting(request,
                                    check_for="timeout",
                                    field_value=int(calltimeout)):
                errors['chk_timeout'] = ["Timeout limit of %s exceeded."\
                    % dialer_setting_limit(request, limit_for="timeout")]

        aleg_gateway_id = bundle.data.get('aleg_gateway')
        if aleg_gateway_id:
            try:
                aleg_gateway_id = Gateway.objects.get(id=aleg_gateway_id).id
                bundle.data['aleg_gateway'] = '/api/v1/gateway/%s/' %\
                                              aleg_gateway_id
            except:
                errors['chk_gateway'] = ["The Gateway ID doesn't exist!"]

        content_type = bundle.data.get('content_type')
        if content_type == 'voice_app' or content_type == 'survey':
            try:
                content_type_id = ContentType.objects\
                .get(app_label=str(content_type)).id
                bundle.data['content_type'] = '/api/v1/contenttype/%s/' %\
                                              content_type_id
            except:
                errors['chk_content_type'] = ["The ContentType doesn't exist!"]
        else:
            errors['chk_content_type'] = [
                "Entered wrong option. Please enter \
                                            'voice_app' or 'survey' !"
            ]

        object_id = bundle.data.get('object_id')
        if object_id:
            try:
                bundle.data['object_id'] = object_id
            except:
                errors['chk_object_id'] = ["App Object ID doesn't exist!"]

        try:
            user_id = User.objects.get(username=request.user).id
            bundle.data['user'] = '******' % user_id
        except:
            errors['chk_user'] = ["The User doesn't exist!"]

        if request.method == 'POST':
            name_count = Campaign.objects.filter(name=bundle.data.get('name'),
                                                 user=request.user).count()
            if (name_count != 0):
                errors['chk_campaign_name'] = ["The Campaign name duplicated!"]

        return errors
Пример #27
0
def contact_import(request):
    """Import CSV file of Contacts for the logged in user

    **Attributes**:

        * ``form`` - Contact_fileImport
        * ``template`` - dialer_contact/contact/import_contact.html

    **Logic Description**:

        * Before adding contacts, check dialer setting limit if applicable
          to the user.
        * Add new contacts which will belong to the logged in user
          via csv file & get the result (upload success and failure
          statistics)

    **Important variable**:

        * total_rows - Total no. of records in the CSV file
        * retail_record_count - No. of records imported from the CSV file
    """
    # Check dialer setting limit
    if request.user and request.method == 'POST':
        # check  Max Number of contacts
        if check_dialer_setting(request, check_for="contact"):
            request.session['msg'] = _("you have too many contacts. you are allowed a maximum of %(limit)s") % \
                {'limit': dialer_setting_limit(request, limit_for="contact")}

            # contact limit reached
            frontend_send_notification(request, NOTIFICATION_NAME.contact_limit_reached)
            return HttpResponseRedirect(redirect_url_to_contact_list)

    form = Contact_fileImport(request.user, request.POST or None, request.FILES or None)
    csv_data = ''
    msg = ''
    error_msg = ''
    success_import_list = []
    type_error_import_list = []
    contact_cnt = 0
    bulk_record = []

    if form.is_valid():
        # col_no - field name
        #  0     - contact
        #  1     - last_name
        #  2     - first_name
        #  3     - email
        #  4     - description
        #  5     - status
        #  6     - address
        #  7     - city
        #  8     - country
        #  9     - country
        # 10     - unit_number
        # 11     - additional_vars
        # To count total rows of CSV file
        records = csv.reader(request.FILES['csv_file'], delimiter='|', quotechar='"')
        total_rows = len(list(records))
        BULK_SIZE = 1000
        csv_data = csv.reader(request.FILES['csv_file'], delimiter='|', quotechar='"')
        #Get Phonebook Obj
        phonebook = get_object_or_404(Phonebook, pk=request.POST['phonebook'], user=request.user)
        #Read each Row
        for row in csv_data:
            row = striplist(row)
            if not row or str(row[0]) == 0:
                continue

            #Check field type
            if not int(row[5]):
                error_msg = _("invalid value for import! please check the import samples or phonebook is not valid")
                type_error_import_list.append(row)
                break

            if len(row[9]) > 2:
                error_msg = _("invalid value for country code, it needs to be a valid ISO 3166-1 alpha-2 codes")
                type_error_import_list.append(row)
                break

            row_11 = ''
            if row[11]:
                try:
                    row_11 = json.loads(row[11])
                except:
                    row_11 = ''

            bulk_record.append(
                Contact(
                    phonebook=phonebook,
                    contact=row[0],
                    last_name=row[1],
                    first_name=row[2],
                    email=row[3],
                    description=row[4],
                    status=int(row[5]),
                    address=row[6],
                    city=row[7],
                    state=row[8],
                    country=row[9],  # Note: country needs to be a country code (CA, ES)
                    unit_number=row[10],
                    additional_vars=row_11)
            )

            contact_cnt = contact_cnt + 1

            if contact_cnt < 100:
                #We want to display only 100 lines of the success import
                success_import_list.append(row)

            if contact_cnt % BULK_SIZE == 0:
                #Bulk insert
                Contact.objects.bulk_create(bulk_record)
                bulk_record = []

        # remaining record
        Contact.objects.bulk_create(bulk_record)
        bulk_record = []

    #check if there is contact imported
    if contact_cnt > 0:
        msg = _('%(contact_cnt)s contact(s) have been uploaded successfully out of %(total_rows)s row(s)!') \
            % {'contact_cnt': contact_cnt, 'total_rows': total_rows}

    data = RequestContext(request, {
        'form': form,
        'csv_data': csv_data,
        'msg': msg,
        'error_msg': error_msg,
        'success_import_list': success_import_list,
        'type_error_import_list': type_error_import_list,
    })
    return render_to_response('dialer_contact/contact/import_contact.html', data, context_instance=RequestContext(request))
Пример #28
0
    def is_valid(self, bundle, request=None):
        errors = {}
        if not bundle.data:
            errors['Data'] = ['Data set is empty']
        startingdate = bundle.data.get('startingdate')
        expirationdate = bundle.data.get('expirationdate')

        if request.method == 'POST':
            startingdate = get_value_if_none(startingdate, time.time())
            # expires in 90 days
            expirationdate = get_value_if_none(expirationdate,
                time.time() + 86400 * 90)
            #Startdate and expirationdate are UTC -> convert to localtime
            startingdate = float(startingdate) - time.altzone
            expirationdate = float(expirationdate) - time.altzone

            bundle.data['startingdate'] = time.strftime('%Y-%m-%d %H:%M:%S',
                time.gmtime(float(startingdate)))
            bundle.data['expirationdate'] = time.strftime('%Y-%m-%d %H:%M:%S',
                time.gmtime(float(expirationdate)))

        if request.method == 'PUT':
            if startingdate:
                bundle.data['startingdate'] = time.strftime(
                    '%Y-%m-%d %H:%M:%S', time.gmtime(float(startingdate)))
            if expirationdate:
                bundle.data['expirationdate'] = time.strftime(
                    '%Y-%m-%d %H:%M:%S', time.gmtime(float(expirationdate)))

        if user_attached_with_dialer_settings(request):
            errors['user_dialer_setting'] = ['Your settings are not \
                    configured properly, Please contact the administrator.']

        if check_dialer_setting(request, check_for="campaign"):
            errors['chk_campaign'] = ["Too many campaigns. Max allowed %s"\
                    % dialer_setting_limit(request, limit_for="campaign")]

        frequency = bundle.data.get('frequency')
        if frequency:
            if check_dialer_setting(request, check_for="frequency",
                field_value=int(frequency)):
                errors['chk_frequency'] = ["Frequency limit of %s exceeded."\
                    % dialer_setting_limit(request, limit_for="frequency")]

        callmaxduration = bundle.data.get('callmaxduration')
        if callmaxduration:
            if check_dialer_setting(request,
                check_for="duration",
                field_value=int(callmaxduration)):
                errors['chk_duration'] = ["Duration limit of %s exceeded."\
                    % dialer_setting_limit(request, limit_for="duration")]

        maxretry = bundle.data.get('maxretry')
        if maxretry:
            if check_dialer_setting(request,
                check_for="retry",
                field_value=int(maxretry)):
                errors['chk_duration'] = ["Retries limit of %s exceeded."\
                    % dialer_setting_limit(request, limit_for="retry")]

        calltimeout = bundle.data.get('calltimeout')
        if calltimeout:
            if check_dialer_setting(request,
                check_for="timeout",
                field_value=int(calltimeout)):
                errors['chk_timeout'] = ["Timeout limit of %s exceeded."\
                    % dialer_setting_limit(request, limit_for="timeout")]

        aleg_gateway_id = bundle.data.get('aleg_gateway')
        if aleg_gateway_id:
            try:
                aleg_gateway_id = Gateway.objects.get(id=aleg_gateway_id).id
                bundle.data['aleg_gateway'] = '/api/v1/gateway/%s/' %\
                                              aleg_gateway_id
            except:
                errors['chk_gateway'] = ["The Gateway ID doesn't exist!"]

        content_type = bundle.data.get('content_type')
        if content_type == 'voice_app' or content_type == 'survey':
            try:
                content_type_id = ContentType.objects\
                .get(app_label=str(content_type)).id
                bundle.data['content_type'] = '/api/v1/contenttype/%s/' %\
                                              content_type_id
            except:
                errors['chk_content_type'] = ["The ContentType doesn't exist!"]
        else:
            errors['chk_content_type'] = ["Entered wrong option. Please enter \
                                            'voice_app' or 'survey' !"]

        object_id = bundle.data.get('object_id')
        if object_id:
            try:
                bundle.data['object_id'] = object_id
            except:
                errors['chk_object_id'] = ["App Object ID doesn't exist!"]

        try:
            user_id = User.objects.get(username=request.user).id
            bundle.data['user'] = '******' % user_id
        except:
            errors['chk_user'] = ["The User doesn't exist!"]

        if request.method == 'POST':
            name_count = Campaign.objects.filter(name=bundle.data.get('name'),
                user=request.user).count()
            if (name_count != 0):
                errors['chk_campaign_name'] = ["The Campaign name duplicated!"]

        return errors