Example #1
0
    def __init__(self, *args, **kwargs):
        super(ContactForm, self).__init__(*args, **kwargs)

        if self.user.is_admin_for(self.user.get_org()):
            self.fields['room'].queryset = Room.get_all(self.user.get_org()).order_by('name')
        else:
            self.fields['room'].queryset = self.user.manage_rooms.all()
Example #2
0
    def __init__(self, *args, **kwargs):
        super(UserForm, self).__init__(*args, **kwargs)

        if self.user.get_org():
            org_rooms = Room.get_all(self.user.get_org()).order_by('name')
            self.fields['rooms'].queryset = org_rooms
            self.fields['manage_rooms'].queryset = org_rooms
Example #3
0
def sync_org_contacts(org_id):
    """
    Syncs all contacts for the given org
    """
    from chatpro.orgs_ext import TaskType
    from chatpro.rooms.models import Room
    from .models import Contact

    org = Org.objects.get(pk=org_id)

    logger.info('Starting contact sync task for org #%d' % org.id)

    sync_fields = [org.get_chat_name_field()]
    sync_groups = [r.uuid for r in Room.get_all(org)]

    created, updated, deleted, failed = sync_pull_contacts(org, Contact, fields=sync_fields, groups=sync_groups)

    task_result = dict(time=datetime_to_ms(timezone.now()),
                       counts=dict(created=len(created),
                                   updated=len(updated),
                                   deleted=len(deleted),
                                   failed=len(failed)))
    org.set_task_result(TaskType.sync_contacts, task_result)

    logger.info("Finished contact sync for org #%d (%d created, %d updated, %d deleted, %d failed)"
                % (org.id, len(created), len(updated), len(deleted), len(failed)))
Example #4
0
    def __init__(self, *args, **kwargs):
        super(UserForm, self).__init__(*args, **kwargs)

        if self.user.get_org():
            org_rooms = Room.get_all(self.user.get_org()).order_by('name')
            self.fields['rooms'].queryset = org_rooms
            self.fields['manage_rooms'].queryset = org_rooms
Example #5
0
    def __init__(self, *args, **kwargs):
        super(ContactForm, self).__init__(*args, **kwargs)

        if self.user.is_admin_for(self.user.get_org()):
            self.fields['room'].queryset = Room.get_all(
                self.user.get_org()).order_by('name')
        else:
            self.fields['room'].queryset = self.user.manage_rooms.all()
Example #6
0
    def test_update_room_groups(self, mock_get_contacts, mock_get_groups):
        mock_get_groups.return_value = [TembaGroup.create(uuid='G-007', name="New group", size=2)]
        mock_get_contacts.return_value = [
            TembaContact.create(uuid='C-007', name="Jan", urns=['tel:123'], groups=['G-007'],
                                fields=dict(chat_name="jan"), language='eng', modified_on=timezone.now()),
            TembaContact.create(uuid='C-008', name="Ken", urns=['tel:234'], groups=['G-007'],
                                fields=dict(chat_name="ken"), language='eng', modified_on=timezone.now())
        ]

        # select one new group
        Room.update_room_groups(self.unicef, ['G-007'])
        self.assertEqual(self.unicef.rooms.filter(is_active=True).count(), 1)
        self.assertEqual(self.unicef.rooms.filter(is_active=False).count(), 3)  # existing de-activated

        new_room = Room.objects.get(uuid='G-007')
        self.assertEqual(new_room.name, "New group")
        self.assertTrue(new_room.is_active)

        # check contact changes
        self.assertEqual(self.unicef.contacts.filter(is_active=True).count(), 2)
        self.assertEqual(self.unicef.contacts.filter(is_active=False).count(), 5)  # existing de-activated

        jan = Contact.objects.get(uuid='C-007')
        self.assertEqual(jan.full_name, "Jan")
        self.assertEqual(jan.chat_name, "jan")
        self.assertEqual(jan.urn, 'tel:123')
        self.assertEqual(jan.room, new_room)
        self.assertTrue(jan.is_active)

        # change group and contacts on chatpro side
        Room.objects.filter(name="New group").update(name="Huh?", is_active=False)
        jan.full_name = "Janet"
        jan.save()
        Contact.objects.filter(full_name="Ken").update(is_active=False)

        # re-select new group
        Room.update_room_groups(self.unicef, ['G-007'])

        # local changes should be overwritten
        self.assertEqual(self.unicef.rooms.get(is_active=True).name, 'New group')
        self.assertEqual(self.unicef.contacts.filter(is_active=True).count(), 2)
        Contact.objects.get(full_name="Jan", is_active=True)
Example #7
0
    def test_create(self):
        testers = Room.create(self.unicef, "Testers", 'G-007')
        jan = Contact.create(self.unicef, self.admin, "Jan", "janet", 'tel:1234', testers, 'C-007')
        bob = User.create(self.unicef, "Bob", "bobby", "*****@*****.**", "pass", False, [testers], [])
        ken = User.create(self.unicef, "Ken", "kenny", "*****@*****.**", "pass", False, [], [testers])

        self.assertEqual(testers.org, self.unicef)
        self.assertEqual(testers.name, "Testers")
        self.assertEqual(testers.uuid, 'G-007')
        self.assertEqual(list(testers.get_contacts()), [jan])
        self.assertEqual(list(testers.get_users().order_by('profile__full_name')), [bob, ken])
        self.assertEqual(list(testers.get_managers()), [ken])
Example #8
0
    def kwargs_from_temba(cls, org, temba_contact):
        org_room_uuids = [r.uuid for r in Room.get_all(org)]
        room_uuids = intersection(org_room_uuids, temba_contact.groups)
        room = Room.objects.get(org=org, uuid=room_uuids[0]) if room_uuids else None

        if not room:
            raise ValueError("No room with uuid in %s" % ", ".join(temba_contact.groups))

        return dict(org=org,
                    full_name=temba_contact.name,
                    chat_name=temba_contact.fields.get(org.get_chat_name_field(), None),
                    urn=temba_contact.urns[0],
                    room=room,
                    uuid=temba_contact.uuid)
Example #9
0
    def _get_or_create_room(org, group_uuid):
        """
        Gets a room by group UUID, or creates it by fetching from Temba instance
        """
        room = Room.objects.filter(org=org, uuid=group_uuid).first()
        if room:
            if not room.is_active:
                room.is_active = True
                room.save(update_fields=('is_active', ))
        else:
            temba_group = org.get_temba_client().get_group(group_uuid)
            room = Room.create(org, temba_group.name, temba_group.uuid)

        return room
Example #10
0
    def _get_or_create_room(org, group_uuid):
        """
        Gets a room by group UUID, or creates it by fetching from Temba instance
        """
        room = Room.objects.filter(org=org, uuid=group_uuid).first()
        if room:
            if not room.is_active:
                room.is_active = True
                room.save(update_fields=('is_active',))
        else:
            temba_group = org.get_temba_client().get_group(group_uuid)
            room = Room.create(org, temba_group.name, temba_group.uuid)

        return room
Example #11
0
    def test_create(self):
        testers = Room.create(self.unicef, "Testers", 'G-007')
        jan = Contact.create(self.unicef, self.admin, "Jan", "janet",
                             'tel:1234', testers, 'C-007')
        bob = User.create(self.unicef, "Bob", "bobby", "*****@*****.**",
                          "pass", False, [testers], [])
        ken = User.create(self.unicef, "Ken", "kenny", "*****@*****.**",
                          "pass", False, [], [testers])

        self.assertEqual(testers.org, self.unicef)
        self.assertEqual(testers.name, "Testers")
        self.assertEqual(testers.uuid, 'G-007')
        self.assertEqual(list(testers.get_contacts()), [jan])
        self.assertEqual(
            list(testers.get_users().order_by('profile__full_name')),
            [bob, ken])
        self.assertEqual(list(testers.get_managers()), [ken])
Example #12
0
    def test_update_room_groups(self, mock_get_contacts, mock_get_groups):
        mock_get_groups.return_value = [
            TembaGroup.create(uuid='G-007', name="New group", size=2)
        ]
        mock_get_contacts.return_value = [
            TembaContact.create(uuid='C-007',
                                name="Jan",
                                urns=['tel:123'],
                                groups=['G-007'],
                                fields=dict(chat_name="jan"),
                                language='eng',
                                modified_on=timezone.now()),
            TembaContact.create(uuid='C-008',
                                name="Ken",
                                urns=['tel:234'],
                                groups=['G-007'],
                                fields=dict(chat_name="ken"),
                                language='eng',
                                modified_on=timezone.now())
        ]

        # select one new group
        Room.update_room_groups(self.unicef, ['G-007'])
        self.assertEqual(self.unicef.rooms.filter(is_active=True).count(), 1)
        self.assertEqual(self.unicef.rooms.filter(is_active=False).count(),
                         3)  # existing de-activated

        new_room = Room.objects.get(uuid='G-007')
        self.assertEqual(new_room.name, "New group")
        self.assertTrue(new_room.is_active)

        # check contact changes
        self.assertEqual(
            self.unicef.contacts.filter(is_active=True).count(), 2)
        self.assertEqual(
            self.unicef.contacts.filter(is_active=False).count(),
            5)  # existing de-activated

        jan = Contact.objects.get(uuid='C-007')
        self.assertEqual(jan.full_name, "Jan")
        self.assertEqual(jan.chat_name, "jan")
        self.assertEqual(jan.urn, 'tel:123')
        self.assertEqual(jan.room, new_room)
        self.assertTrue(jan.is_active)

        # change group and contacts on chatpro side
        Room.objects.filter(name="New group").update(name="Huh?",
                                                     is_active=False)
        jan.full_name = "Janet"
        jan.save()
        Contact.objects.filter(full_name="Ken").update(is_active=False)

        # re-select new group
        Room.update_room_groups(self.unicef, ['G-007'])

        # local changes should be overwritten
        self.assertEqual(
            self.unicef.rooms.get(is_active=True).name, 'New group')
        self.assertEqual(
            self.unicef.contacts.filter(is_active=True).count(), 2)
        Contact.objects.get(full_name="Jan", is_active=True)
Example #13
0
 def test_get_all(self):
     self.assertEqual(len(Room.get_all(self.unicef)), 3)
     self.assertEqual(len(Room.get_all(self.nyaruka)), 1)
Example #14
0
 def calculate():
     # org admins have implicit access to all rooms
     if user.is_admin_for(org):
         return Room.get_all(org)
     else:
         return user.rooms.filter(is_active=True)
Example #15
0
 def calculate():
     # org admins have implicit access to all rooms
     if user.is_admin_for(org):
         return Room.get_all(org)
     else:
         return user.rooms.filter(is_active=True)
Example #16
0
 def create_room(self, org, name, uuid):
     return Room.create(org, name, uuid)
Example #17
0
 def test_get_all(self):
     self.assertEqual(len(Room.get_all(self.unicef)), 3)
     self.assertEqual(len(Room.get_all(self.nyaruka)), 1)
Example #18
0
 def create_room(self, org, name, uuid):
     return Room.create(org, name, uuid)