summaryrefslogtreecommitdiffstats
path: root/welco/views.py
blob: 2efa6f3a32961a29e9ed69498cec534cc8147e33 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
# welco - multichannel request processing
# Copyright (C) 2015  Entr'ouvert
#
# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

import json

from django.conf import settings
from django.contrib.auth import logout as auth_logout
from django.contrib.auth import views as auth_views
from django.contrib.auth.decorators import login_required
from django.contrib.contenttypes.models import ContentType
from django.core.exceptions import PermissionDenied
from django.core.urlresolvers import reverse
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import resolve_url
from django import template
from django.template import RequestContext
from django.utils.encoding import force_text
from django.utils.http import quote
from django.utils.translation import ugettext_lazy as _
from django.views.decorators.csrf import csrf_exempt
from django.views.generic import TemplateView

try:
    from mellon.utils import get_idps
except ImportError:
    get_idps = lambda: []

from sources.mail.views import Home as MailHome
from sources.phone.views import Home as PhoneHome
from sources.counter.views import Home as CounterHome
from .qualif.models import Association
from .kb.views import HomeZone as KbHomeZone, check_user_perms as check_kb_user_perms
from .contacts.views import HomeZone as ContactsHomeZone
from .forms import QualificationForm


def login(request, *args, **kwargs):
    if any(get_idps()):
        if not 'next' in request.GET:
            return HttpResponseRedirect(resolve_url('mellon_login'))
        return HttpResponseRedirect(resolve_url('mellon_login') + '?next='
                                    + quote(request.GET.get('next')))
    return auth_views.login(request, *args, **kwargs)

def logout(request, next_page=None):
    if any(get_idps()):
        return HttpResponseRedirect(resolve_url('mellon_logout'))
    auth_logout(request)
    if next_page is not None:
        next_page = resolve_url(next_page)
    else:
        next_page = '/'
    return HttpResponseRedirect(next_page)


class Qualification(TemplateView):
    template_name = 'welco/qualification_no_validation.html'

    def get_context_data(self, **kwargs):
        context = super(Qualification, self).get_context_data(**kwargs)
        context['form'] = QualificationForm(self.request.user)
        context['source_type'] = self.request.GET['source_type']
        source_type = ContentType.objects.get(id=self.request.GET['source_type'])
        context['source_type_name'] = source_type.model
        context['source_pk'] = self.request.GET['source_pk']
        if self.request.GET.get('source_pk'):
            context['associations'] = Association.objects.filter(
                    source_type=ContentType.objects.get(id=self.request.GET['source_type']),
                    source_pk=self.request.GET['source_pk']).order_by('id')
        return context

    def post(self, request, *args, **kwargs):
        association = Association(
                source_type=ContentType.objects.get(id=request.POST['source_type']),
                source_pk=request.POST['source_pk'])
        association.formdef_reference = request.POST['formdef_reference']
        association.save()
        request.GET = request.POST
        return self.get(request)

qualification = csrf_exempt(Qualification.as_view())


class ChannelHome(TemplateView):
    template_name = 'welco/home.html'
    source_klass = MailHome

    def check_user_ok(self):
        user_groups = set([x.name for x in self.request.user.groups.all()])
        channel_groups = set(settings.CHANNEL_ROLES[self.source_klass.source_key])
        return user_groups.intersection(channel_groups)

    def get_context_data(self, **kwargs):
        if not self.check_user_ok():
            raise PermissionDenied()
        context = super(ChannelHome, self).get_context_data(**kwargs)
        context['panels'] = [
                {'key': x, 'zone_url': x + '-zone'} for x in settings.SCREEN_PANELS]
        context['source'] = self.source_klass(self.request, **kwargs)
        context['kb'] = KbHomeZone(self.request)
        context['contacts'] = ContactsHomeZone(self.request)
        context['channels'] = []

        user_groups = set([x.name for x in self.request.user.groups.all()])
        for channel in settings.CHANNEL_ROLES:
            channel_groups = set(settings.CHANNEL_ROLES[channel])
            if user_groups.intersection(channel_groups):
                context['channels'].append(channel)
        return context


@login_required
def home(request):
    user_groups = set([x.name for x in request.user.groups.all()])
    for channel in settings.CHANNEL_ROLES:
        channel_groups = set(settings.CHANNEL_ROLES[channel])
        if user_groups.intersection(channel_groups):
            return HttpResponseRedirect('%s/' % channel)
    raise PermissionDenied()

class HomePhone(ChannelHome):
    source_klass = PhoneHome

home_phone = login_required(HomePhone.as_view())


class HomeMail(ChannelHome):
    source_klass = MailHome

home_mail = login_required(HomeMail.as_view())

class HomeCounter(ChannelHome):
    source_klass = CounterHome

home_counter = login_required(HomeCounter.as_view())


@login_required
def wcs_summary(request, *args, **kwargs):
    source_class = ContentType.objects.get(id=kwargs.get('source_type')).model_class()
    source_object = source_class.objects.get(id=kwargs.get('source_pk'))
    tmpl_name = 'welco/%s_summary.html' % source_class._meta.app_label
    tmpl = template.loader.get_template(tmpl_name)
    context = {}
    context['site_base'] = request.build_absolute_uri('/')[:-1]
    context['object'] = source_object
    json_str = json.dumps({'content': tmpl.render(context, request=request)})
    for variable in ('jsonpCallback', 'callback'):
        if variable in request.GET:
            json_str = '%s(%s);' % (request.GET[variable], json_str)
            break
    return HttpResponse(json_str, content_type='application/javascript')

@login_required
def remove_association(request, *args, **kwargs):
    Association.objects.filter(id=kwargs.get('pk')).delete()
    return HttpResponseRedirect(resolve_url('home'))

@login_required
@csrf_exempt
def create_formdata(request, *args, **kwargs):
    response = HttpResponse(content_type='application/json')
    if request.method != 'POST':
        json.dump({'err': 1}, response)
        return response

    qualif = Association.objects.get(id=kwargs.get('pk'))
    try:
        qualif.push(request)
    except Exception, e:
        json.dump({'err': 1, 'msg': str(e)}, response)
        return response
    json.dump({'result': 'ok', 'url': qualif.formdata_url}, response)
    return response

@login_required
def menu_json(request):
    response = HttpResponse(content_type='application/json')
    user_groups = set([x.name for x in request.user.groups.all()])
    menu = []
    labels = {
        'mail': _('Mails'),
        'phone': _('Call Center'),
        'counter': _('Counter'),
    }
    for channel in settings.CHANNEL_ROLES:
        channel_groups = set(settings.CHANNEL_ROLES[channel])
        if user_groups.intersection(channel_groups):
            menu.append({
                'label': force_text(labels.get(channel)),
                'slug': channel,
                'url': request.build_absolute_uri(reverse('home-%s' % channel)),
            })
    if check_kb_user_perms(request.user, access=True):
        menu.append({
            'label': force_text(_('Knowledge Base')),
            'slug': 'book',
            'url': request.build_absolute_uri(reverse('kb-home'))
            })
    json_str = json.dumps(menu)
    for variable in ('jsonpCallback', 'callback'):
        if variable in request.GET:
            response = HttpResponse(content_type='application/javascript')
            json_str = '%s(%s);' % (request.GET[variable], json_str)
            break
    response.write(json_str)
    return response