Пример #1
0
 def test_get_by_email(self):
     with self.assertRaises(Case.DoesNotExist):
         Case.get_by_email('*****@*****.**')
         Case.get_by_email('*****@*****.**')
     obj = CaseFactory(pk=22)
     obj2 = Case.get_by_email('*****@*****.**')
     self.assertEqual(obj, obj2)
Пример #2
0
 def test_get_by_email(self):
     with self.assertRaises(Case.DoesNotExist):
         Case.get_by_email('*****@*****.**')
         Case.get_by_email('*****@*****.**')
     obj = CaseFactory(pk=22)
     obj2 = Case.get_by_email('*****@*****.**')
     self.assertEqual(obj, obj2)
Пример #3
0
    def get_queryset(self):
        organization_id = self.request.user.organization_id
        child_id = self.request.query_params.get("child_id", None)
        is_active = self.request.query_params.get("is_active", False)

        if is_active == "all":
            return Case.get_web_queryset(
                child_id, organization_id).exclude(status="archived")
        elif is_active == "true":
            return Case.get_web_queryset(
                child_id, organization_id).filter(status="active")
        elif is_active == "false":
            return Case.get_web_queryset(
                child_id, organization_id).filter(status="closed")
        elif is_active == "archived":
            return Case.get_web_queryset(
                child_id, organization_id).filter(status="archived")
        else:
            return Case.get_web_queryset(child_id, organization_id)
Пример #4
0
def AddCase(row_data):
    """
    create Case từ một row data trong file
    """
    stt = row_data[0]
    name = row_data[1]
    status = row_data[2]
    priority = row_data[3]
    case_type = row_data[4]
    accountName = row_data[5]
    contact = row_data[6]
    description = row_data[7]
    assigned_to = row_data[8]
    teamName = row_data[9]

    case = FindCaseByName(name)
    if case is None:
        case = Case()
Пример #5
0
class CaseModelTestCase(CaseCreation, TestCase):

    def test_string_representation(self):
        case = Case(name='name', )
        self.assertEqual(str(case), case.name)
Пример #6
0
class NewCaseForm(SingleButtonMixin, PartialMixin, GIODOMixin, autocomplete_light.ModelForm):
    attachment_cls = Attachment
    attachment_rel_field = 'letter'
    attachment_file_field = 'attachment'
    action_text = _("Report case")

    client = forms.ModelChoiceField(queryset=get_user_model().objects.none(),
                                    label=_("Client"),
                                    required=False,
                                    help_text=CLIEN_FIELD_TEXT,
                                    widget=autocomplete_light.ChoiceWidget('UserAutocomplete'))
    email = forms.EmailField(required=False,
                             label=_("User e-mail"))
    email_registration = UserEmailField(required=True,
                                        help_text=EMAIL_TEXT,
                                        label=_("E-mail"))

    def __init__(self, *args, **kwargs):
        self.user = kwargs.pop('user')
        super(NewCaseForm, self).__init__(*args, **kwargs)
        self.helper.form_tag = False
        self.helper.form_method = 'post'
        self.fields['name'].help_text = CASE_NAME_TEXT

        if self._is_super_staff():
            self.fields['client'].initial = self.user
            self.fields['client'].queryset = (get_user_model().objects.
                                              for_user(self.user).all())
        else:
            del self.fields['client']
            del self.fields['email']

        if not self.user.is_anonymous():  # is registered
            del self.fields['email_registration']

        if not (self.user.is_anonymous() or self._is_super_staff()):
            del self.fields['giodo']
        elif self._is_super_staff():
            self.fields['giodo'].required = False

    def _is_super_staff(self):
        return self.user.has_perm('cases.can_select_client')

    def clean(self):
        if self.user.has_perm('cases.can_select_client') and \
                not (self.cleaned_data.get('email') or self.cleaned_data.get('client')):
            raise ValidationError(_("Have to enter user email or select a client"))
        return super(NewCaseForm, self).clean()

    def get_user(self):
        if self.user.is_anonymous():
            return get_user_model().objects.get_by_email_or_create(
                self.cleaned_data['email_registration'])
        return self.user

    def get_client(self, user):
        if self.user.is_anonymous() and self.cleaned_data['email_registration']:
            return user
        if not self.user.has_perm('cases.can_select_client'):
            return self.user
        elif self.cleaned_data['client']:
            return self.cleaned_data['client']
        elif self.cleaned_data['email']:
            return get_user_model().objects.get_by_email_or_create(self.cleaned_data['email'])
        return self.user

    def get_case(self, client, user):
        case = Case(name=self.cleaned_data['name'], created_by=user, client=client)
        case.save()
        return case
Пример #7
0
 def get_case(self, client, user):
     case = Case(name=self.cleaned_data['name'], created_by=user, client=client)
     case.save()
     return case
Пример #8
0
        print("Delete .eml from {email} as auto-replied".format(
            email=message.from_address[0]))
        message.eml.delete(save=True)
        return

    # Identify user
    user = get_user_model().objects.get_by_email_or_create(
        message.from_address[0])
    print("Identified user: "******"Case creating")
        case = Case(name=message.subject, created_by=user, client=user)
        case.save()
        user.notify(actor=user,
                    verb='registered',
                    target=case,
                    from_email=case.get_email())
    print("Case: ", case)
    # Prepare text
    if message.text:
        text = quotations.extract_from(message.text, 'text/plain')
        signature = message.text.replace(text, '')
    else:
        text = html2text.html2text(
            quotations.extract_from(message.html, 'text/html'))
        signature = message.text.replace(text, '')
Пример #9
0
def dashboard(request):
    print('test')
    server = "imap.gmail.com"
    port = '993'
    a_email = "*****@*****.**"
    pwd = "zoogle@123 "
    imap = imaplib.IMAP4_SSL(server, port)
    imap.login(a_email, pwd)
    imap.select('INBOX')
    status, response = imap.search(None, '(UNSEEN)')

    unread_msg_nums = response[0].split()
    count = len(unread_msg_nums)
    print(count)
    email_ids = [e_id for e_id in response[0].split()]
    print("........................................")
    print(email_ids)

    if email_ids:

        for e_id in email_ids:
            print("=======", e_id)
            _, response = imap.fetch(e_id, '(RFC822)')
            r = response[0][1][9:]

            email_message = email.message_from_bytes(r)
            subject = email_message['subject']

            print("SUBJECT:", subject)
            # s = word_tokenize(subject)
            # print("NLP:",word_tokenize(subject))
            ##################################################
            e_from = email_message['from']
            print(e_from)

            ################# From address username ###########
            e_user = e_from.split('<')
            # print(e_user)
            e_username = e_user[0].capitalize()
            print("USERNAME:"******"Email FROM ADDRESS:", email_address)
            ###################################################
            e_to = email_message['to']
            a_to = re.findall(
                "([a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+)", e_to)
            to = a_to[0]
            print("EMAIL TO ADDRESS:", to)
            if email_message.is_multipart():
                for part in email_message.walk():
                    if part.get_content_type() == "text/plain":
                        body = part.get_payload()
                        print('**************', body)
                        e_inbox = Inbox(subject_inbox=subject,
                                        description=body,
                                        username=e_username,
                                        from_address=email_address,
                                        to_address=to,
                                        status=1)
                        e_inbox.save()
                        status = "Open"
                        sla_time = Sla.objects.values(
                            'voiceopen_respond_within').filter(
                                voiceopen_status=status)
                        print(sla_time, ":time")
                        counts_case = Case.objects.all().count()
                        print('8888888888888888888888888888', counts_case)
                        addcase = counts_case + 1
                        # print("--------",addcase)
                        ccase = "C_00" + str(addcase)
                        print('==========ssss', ccase)
                        c_case = Case(name=e_username,
                                      email=email_address,
                                      status=status,
                                      case_number=ccase,
                                      creation_date=datetime.datetime.now())
                        c_case.save()
                        for s in sla_time:
                            print("*****")
                            u_sla = s['voiceopen_respond_within']
                            print("sla:", u_sla)
                            h = u_sla.strftime('%H')
                            print('hours:', h)
                            m = u_sla.strftime('%M')
                            s = u_sla.strftime('%S')
                            print("*(()*", s)
                            l = Case.objects.values_list(
                                'id', flat=True).latest('id')
                            print("L:", l)
                            cd = Case.objects.values_list(
                                'created_on', flat=True).latest('id')
                            print("current:", cd.time())
                            add = cd + datetime.timedelta(
                                hours=int(h), minutes=int(m), seconds=int(s))
                            print("add:", add)
                            c = Case.objects.filter(id=l).update(sla=add)
                            print("C:", c)

                        print('=============')
    ebox = Inbox.objects.all()

    return render(request, 'mailbox.html', {'ebox': ebox})
Пример #10
0
def emailscheck(request):
    a_email="*****@*****.**"
    pwd="vitae2304"
    server = "imap.gmail.com"
    port="993"
    imap = imaplib.IMAP4_SSL(server, port)
    imap.login(a_email,pwd)
    imap.select('INBOX')
    
    ###------To get count of unread mail from particular user-----####
    status, response = imap.search(None, '(UNSEEN)')
    unread_msg_nums = response[0].split()
    count = len(unread_msg_nums)
    print('********',count)
    email_ids = [e_id for e_id in response[0].split()]
    print("........................................")
    print(email_ids)
    a={}
    if email_ids:

        for e_id in email_ids:
            print("=======",e_id)
            _, response = imap.fetch(e_id, '(RFC822)')
            r=response[0][1][9:] 

            email_message = email.message_from_bytes(r)
            subject = email_message['subject']
            
            print("SUBJECT:",subject)
            ##################################################
            e_from = email_message['from']
            print(e_from)
            
            ################# From address username ###########
            e_user = e_from.split('<')
            print(e_user)
            e_username=e_user[0].capitalize()
            print("USERNAME:"******"global email address:",a)
            print("Email FROM ADDRESS:",email_address)
            ###################################################
            e_to = email_message['to']
            a_to = re.findall("([a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+)",e_to)
            to = a_to[0]
            print("EMAIL TO ADDRESS:",to)
            if email_message.is_multipart():

                for part in email_message.walk():
                    if part.get_content_type() == "text/plain":
                        body = part.get_payload()
                        print('body:',body)
                        
                        if (Contact.objects.filter(email=email_address).exists()):
                            print("exist")
                            # channel_layer = get_channel_layer()
                            # async_to_sync(channel_layer.group_send)("gossip", 
                            # {"type": "user.gossip",
                            # "event": "emailnewcase",
                            # "newemailcase": email_address,
                            # })
                            # e_inbox = Emailinfo(subject_inbox=subject,description=body,username=e_username,from_address=email_address,to_address=to,status=1)
                            # e_inbox.save()
                            # name=Contact.objects.values_list('first_name',flat=True).get(email=email_address)
                            # print('first_name:',name)
                            createcontact=Case(name=email_address,description=body)
                            createcontact.save()
                            
                        else:
                            e_inbox = Emailinfo(subject_inbox=subject,description=body,username=e_username,from_address=email_address,to_address=to,status=1)
                            e_inbox.save()
                            # print(s[0])
                            newemail=Contact(email=email_address,first_name=email_address,last_name="by-mail")
                            newemail.save()
                            createcontact=Case(name=email_address,description=body)
                            createcontact.save()
                            print('new contact')                            
    getmail=Emailinfo.objects.values('from_address','id')
    return render(request, 'sales/email.html',{'email':getmail})
Пример #11
0
            return Response(data=data)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

@api_view(['DELETE',])
def api_delete_cases_view(request, id):
    try:
        case = Case.objects.get(pk=id)
    except Case.DoesNotExist:
        return Response(status=status.HTTP_404_NOT_FOUND)

    if request.method == "DELETE":
        operation = case.delete()
        data = {}
        if operation:
            data["message"] = "Case deleted sucessfully."
        else:
            data["message"] = "Case delete failed"
        return Response(data=data) 


@api_view(['POST',])
def api_create_cases_view(request):
    
    case = Case()

    if request.method == "POST":
        serializer = CaseSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Пример #12
0
 def case_get_absolute_url(self):
     return Case(pk=self.case_id).get_absolute_url()
Пример #13
0
 def get_users_with_perms(self, *args, **kwargs):
     return Case(pk=self.case_id).get_users_with_perms()