views.py 15.2 KB
Newer Older
1 2 3
from outils.common_imports import *
from outils.for_view_imports import *

4 5
from django.urls import reverse

6
from outils.common import Verification
7
from outils.common import MConfig
8 9
from members.models import CagetteMember
from shifts.models import CagetteShift
10
from members_space.models import CagetteMembersSpace
11 12

import hashlib
13
import re
14 15 16 17 18 19 20 21 22 23


def _get_response_according_to_credentials(request, credentials, context, template):
    response = HttpResponse(template.render(context, request))
    if ('token' in credentials and 'auth_token' in credentials):
        response.set_cookie('id', credentials['id'])
        response.set_cookie('token', credentials['token'])
        response.set_cookie('auth_token', credentials['auth_token'])
        response.set_cookie('deconnect_option', 'true')
    return response
24

25 26
def index(request, exception=None):
    """Display main screen for the members space"""
27

28
    credentials = CagetteMember.get_credentials(request)
29

30 31
    context = {
        'title': 'Espace Membre',
Félicie committed
32
        'COMPANY_LOGO': getattr(settings, 'COMPANY_LOGO', None),
33 34
        'block_actions_for_attached_people' : getattr(settings, 'BLOCK_ACTIONS_FOR_ATTACHED_PEOPLE', True),
        'permanent_message': getattr(settings, 'PERMANENT_MESSAGE_BELOW_CONNECTION_FIELDS', None),
Félicie committed
35
        'block_service_exchange_24h_before' : getattr(settings, 'BLOCK_SERVICE_EXCHANGE_24H_BEFORE', True),
36
        'ALLOW_BOTH_AS_ANSWER_TO_WHO_IS_COMING_TO_SHIFT' : getattr(settings, 'ALLOW_BOTH_AS_ANSWER_TO_WHO_IS_COMING_TO_SHIFT', True)
37
    }
38

39
    template = loader.get_template('members_space/index.html')
40

41 42 43 44
    if ('failure' in credentials):
        # Bad credentials (or none)
        template = loader.get_template('website/connect.html')
        context['msg'] = ''
45
        context['external_msg'] = request.GET.get('msg')
46 47
        if 'msg' in credentials:
            context['msg'] = credentials['msg']
48 49 50 51 52
        if getattr(settings, 'USE_MEMBERS_CUSTOM_PASSWORD', False) is True:
            context['password_placeholder'] = "Mot de passe ou naissance"
            context['reset_password_available'] = True
        else:
            context['password_placeholder'] = 'Naissance (jjmmaaaa)'
53
        context['is_member_space'] = True
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
    elif ('validation_state' in credentials) and credentials['validation_state'] == 'waiting_validation_member':
        # First connection, until the member validated his account
        template = loader.get_template('members/validation_coop.html')

        referer = request.META.get('HTTP_REFERER')

        doc = CagetteMember.get_couchdb_data(credentials['login'])

        if len(doc) > 1:
            context = {'title': 'Validation inscription',
                       'coop': json.dumps(doc),
                       'coop_msg': doc.get('coop_msg'),
                       'warning_placeholder':
                       """Signaler ici une anomalie du formulaire,
                       un problème lié à votre souscription""",
                       'referer': referer,
                       'mag_place_string': settings.MAG_NAME,
                       'office_place_string': settings.OFFICE_NAME,
                       'max_begin_hour': settings.MAX_BEGIN_HOUR,
                       'payment_meanings': settings.SUBSCRIPTION_PAYMENT_MEANINGS,
                       'em_url': settings.EM_URL,
                       'WELCOME_ENTRANCE_MSG': settings.WELCOME_ENTRANCE_MSG,
                       'WELCOME_SUBTITLE_ENTRANCE_MSG': getattr(settings, 'WELCOME_SUBTITLE_ENTRANCE_MSG', '')}
            if hasattr(settings, 'SUBSCRIPTION_ASK_FOR_SEX'):
                context['ask_for_sex'] = settings.SUBSCRIPTION_ASK_FOR_SEX
79 80
            if hasattr(settings, 'SUBSCRIPTION_ASK_FOR_JOB'):
                context['ask_for_job'] = settings.SUBSCRIPTION_ASK_FOR_JOB
81 82 83 84 85 86 87 88 89 90 91 92
            if hasattr(settings, 'SUBSCRIPTION_ADD_STREET2'):
                context['ask_for_street2'] = settings.SUBSCRIPTION_ADD_STREET2
            if hasattr(settings, 'SUBSCRIPTION_ADD_SECOND_PHONE'):
                context['ask_for_second_phone'] = settings.SUBSCRIPTION_ADD_SECOND_PHONE
    else:
        # Members space
        if 'id' in request.COOKIES:
            partner_id = request.COOKIES['id']
        else:
            partner_id = credentials['id']

        cs = CagetteShift()
93

94 95
        partnerData = cs.get_data_partner(partner_id)

96 97 98 99 100
        default_not_allowed_shift_op = """Désolé ! Le service que tu souhaites échanger démarre dans trop peu de temps.
                                          Afin de faciliter la logistique des services, il n'est plus possible de l'échanger. 
                                          Si tu ne peux vraiment pas venir, tu seras noté.e absent.e à ton service. 
                                          Tu devras alors sélectionner un service de rattrapage sur ton espace membre."""

101 102 103 104
        if 'create_date' in partnerData:
            md5_calc = hashlib.md5(partnerData['create_date'].encode('utf-8')).hexdigest()
            partnerData['verif_token'] = md5_calc

105
            # look for parent for associated partner
106 107 108
            if partnerData["parent_id"] is not False:
                partnerData["parent_name"] = partnerData["parent_id"][1]
                partnerData["parent_id"] = partnerData["parent_id"][0]
Félicie committed
109 110
                md5_calc = hashlib.md5(partnerData['parent_create_date'].encode('utf-8')).hexdigest()
                partnerData['parent_verif_token'] = md5_calc
111
                partnerData['makeups_to_do'] = partnerData['parent_makeups_to_do']
112
                partnerData['extra_shift_done'] = partnerData["parent_extra_shift_done"]
Félicie committed
113

114 115 116
            else:
                partnerData["parent_name"] = False

117 118 119 120 121 122 123 124 125 126
            # look for associated partner for parents
            cm = CagetteMember(partner_id)
            associated_partner = cm.search_associated_people()

            partnerData["associated_partner_id"] = False if associated_partner is None else associated_partner["id"]
            partnerData["associated_partner_name"] = False if associated_partner is None else associated_partner["name"]

            if (associated_partner is not None and partnerData["associated_partner_name"].find(str(associated_partner["barcode_base"])) == -1):
                partnerData["associated_partner_name"] = str(associated_partner["barcode_base"]) + ' - ' + partnerData["associated_partner_name"]

127
            m = CagetteMembersSpace()
128
            context['show_faq'] = getattr(settings, 'MEMBERS_SPACE_FAQ_TEMPLATE', 'members_space/faq.html')
129
            context['show_abcd_calendar'] = getattr(settings, 'SHOW_ABCD_CALENDAR_TAB', True)
130 131
            partnerData["comite"] = m.is_comite(partner_id)

132 133
            context['partnerData'] = partnerData

134 135
            context['mag_name'] = getattr(settings, 'MAG_NAME', '')

136 137
            # Days to hide in the calendar
            days_to_hide = "0"
138 139
            context['SHIFTS_MOVING_ALLOWED'] = getattr(settings, 'SHIFTS_MOVING_ALLOWED', '')
            context['ALLOW_FTOP_TO_DELETE_SHIFT'] = getattr(settings, 'ALLOW_FTOP_TO_DELETE_SHIFT', False)
140 141 142 143
            context['ADDITIONAL_INFO_SHIFT_PAGE'] = getattr(settings, 'ADDITIONAL_INFO_SHIFT_PAGE', '')
            if hasattr(settings, 'SHIFT_EXCHANGE_DAYS_TO_HIDE'):
                days_to_hide = settings.SHIFT_EXCHANGE_DAYS_TO_HIDE
            context['daysToHide'] = days_to_hide
144 145 146 147 148
            # message shown when not allowed to move shift
            context['not_allowed_shift_op'] = getattr(settings, 'NOT_ALLOWED_SHIFT_OP_MSG', default_not_allowed_shift_op)
            context['not_allowed_shift_op'] = re.sub(r"\r\s( *)", "\n", context['not_allowed_shift_op'], flags=re.MULTILINE)
            context['not_allowed_shift_op'] = re.sub(r"\n( *)", "\n", context['not_allowed_shift_op'], flags=re.MULTILINE)

Yvon Kerdoncuff committed
149
            context['canAddShift'] = "true" if getattr(settings, 'CAN_ADD_SHIFT', False) is True else "false"
150 151

            msettings = MConfig.get_settings('members')
152
            context['forms_link'] = msettings['forms_link']['value'] if 'forms_link' in msettings else ''
153 154 155 156 157 158
            context['unsuscribe_form_link'] = ( msettings['unsuscribe_form_link']['value'] 
                if 'unsuscribe_form_link' in msettings 
                else '')
            context['abcd_calendar_link'] = ( msettings['abcd_calendar_link']['value'] 
                if 'abcd_calendar_link' in msettings 
                else '')
159 160 161 162 163 164 165 166 167 168 169 170 171 172
            context['request_form_link'] = msettings['request_form_link']['value'] if 'request_form_link' in msettings else ''
            context['late_service_form_link'] = msettings['late_service_form_link']['value'] if 'late_service_form_link' in msettings else ''
            context['change_template_form_link'] = msettings['change_template_form_link']['value'] if 'change_template_form_link' in msettings else ''
            context['associated_subscribe_form_link'] = msettings['associated_subscribe_form_link']['value'] if 'associated_subscribe_form_link' in msettings else ''
            context['associated_unsubscribe_form_link'] = msettings['associated_unsubscribe_form_link']['value'] if 'associated_unsubscribe_form_link' in msettings else ''
            context['template_unsubscribe_form_link'] = msettings['template_unsubscribe_form_link']['value'] if 'template_unsubscribe_form_link' in msettings else ''
            context['change_email_form_link'] = msettings['change_email_form_link']['value'] if 'change_email_form_link' in msettings else ''
            context['coop_unsubscribe_form_link'] = msettings['coop_unsubscribe_form_link']['value'] if 'coop_unsubscribe_form_link' in msettings else ''
            context['sick_leave_form_link'] = msettings['sick_leave_form_link']['value'] if 'sick_leave_form_link' in msettings else ''
            context['underage_subscribe_form_link'] = msettings['underage_subscribe_form_link']['value'] if 'underage_subscribe_form_link' in msettings else ''
            context['helper_subscribe_form_link'] = msettings['helper_subscribe_form_link']['value'] if 'helper_subscribe_form_link' in msettings else ''
            context['helper_unsubscribe_form_link'] = msettings['helper_unsubscribe_form_link']['value'] if 'helper_unsubscribe_form_link' in msettings else ''
            context['covid_form_link'] = msettings['covid_form_link']['value'] if 'covid_form_link' in msettings else ''
            context['covid_end_form_link'] = msettings['covid_end_form_link']['value'] if 'covid_end_form_link' in msettings else ''
173
            context['on_picking_shift_template_msg'] = msettings['on_picking_shift_template_msg']['value'] if 'on_picking_shift_template_msg' in msettings else ''
174 175 176 177 178 179 180 181
            if getattr(settings, 'USE_EXEMPTIONS_SHIFT_TEMPLATE', False) is True:
                exemptions_shift_id = CagetteServices.get_exemptions_shift_id()
                if exemptions_shift_id is None:
                    return HttpResponse("Le créneau des exemptions n'est pas configuré dans Odoo !")
                else:
                    context['exemptions_shift_id'] = exemptions_shift_id
            else:
                context['exemptions_shift_id'] = 0
182 183 184 185 186 187
        else:
            # may arrive when switching database without cleaning cookie
            return redirect('/website/deconnect')

    return _get_response_according_to_credentials(request, credentials, context, template)

188
def home(request):
189 190 191 192 193 194
    """ 
        Endpoint the front-end will call to load the "home" page. 

        Consequently, the front-end url should be unknown from the server so the user is redirected to the index,
        then the front-end index will call this endpoint to load the home page
    """
195
    template = loader.get_template(getattr(settings, 'MEMBERS_SPACE_HOME_TEMPLATE', 'members_space/home.html'))
196 197 198 199 200 201 202 203 204
    coop_can_change_shift_template = getattr(settings, 'COOP_CAN_CHANGE_SHIFT_TEMPLATE', False)
    if coop_can_change_shift_template is True:
        # make further investigation only if COOP_CAN_CHANGE_SHIFT_TEMPLATE is True
        if 'id' in request.COOKIES:
            partner_id = request.COOKIES['id']
        cs = CagetteShift()
        partnerData = cs.get_data_partner(partner_id)
        if partnerData['cooperative_state'] == "unsubscribed":
            coop_can_change_shift_template = False
205
        if getattr(settings, 'ASSOCIATE_PEOPLE_CAN_CHANGE_SHIFT_TEMPLE_REGISTRATION', False) is False:
206
            if partnerData['suppleant_member_id']:
207
                coop_can_change_shift_template = False
208 209
    context = {
        'title': 'Espace Membres',
210
        'coop_can_change_shift_template': coop_can_change_shift_template,
211
        'max_begin_hour': settings.MAX_BEGIN_HOUR,
212
    }
213 214 215 216 217 218
    # Get messages to display
    msettings = MConfig.get_settings('members')
    if 'msg_accueil' in msettings:
        context['msg_accueil'] = msettings['msg_accueil']['value']
    if 'shop_opening_hours' in msettings:
        context['shop_opening_hours'] = msettings['shop_opening_hours']['value']
219 220
    return HttpResponse(template.render(context, request))

221
def my_info(request):
222
    """ Endpoint the front-end will call to load the "My info" page. """
223
    template = loader.get_template('members_space/my_info.html')
224 225
    context = {
        'title': 'Mes Infos',
226 227
        'understand_my_status': getattr(settings, 'MEMBERS_SPACE_SHOW_UNDERSTAND_MY_STATUS', True),
        'understand_my_status_template': getattr(settings, 'MEMBERS_SPACE_UNDERSTAND_MY_STATUS_TEMPLATE', "members_space/understand_my_status.html")
228 229 230 231
    }
    return HttpResponse(template.render(context, request))

def my_shifts(request):
232
    """ Endpoint the front-end will call to load the "My shifts" page. """
233
    template = loader.get_template('members_space/my_shifts.html')
234 235 236 237 238 239
    context = {
        'title': 'Mes Services',
    }
    return HttpResponse(template.render(context, request))

def shifts_exchange(request):
240
    """ Endpoint the front-end will call to load the "Shifts exchange" page. """
241
    template = loader.get_template('members_space/shifts_exchange.html')
242
    m = CagetteMembersSpace()
243 244
    context = {
        'title': 'Échange de Services',
245
        'canAddShift': getattr(settings, 'CAN_ADD_SHIFT', False),
246 247 248
    }
    return HttpResponse(template.render(context, request))

Etienne Freiss committed
249
def faqBDM(request):
250 251 252 253 254 255
    template_path = getattr(settings, 'MEMBERS_SPACE_FAQ_TEMPLATE', 'members_space/faq.html')
    content = ''
    if template_path:
        template = loader.get_template(template_path)
        context = {
            'title': 'foire aux questions',
256
            'MEMBERS_GUIDE_URL': getattr(settings, 'MEMBERS_GUIDE_URL', None)
257 258 259 260
        }
        content = template.render(context, request)

    return HttpResponse(content)
261

262
def no_content(request):
263
    """ Endpoint the front-end will call to load the "No content" page. """
264
    template = loader.get_template('members_space/no_content.html')
265 266
    context = {
        'title': 'Contenu non trouvé',
267
    }
268 269
    return HttpResponse(template.render(context, request))

270
def get_shifts_history(request):
271 272 273
    res = {}
    partner_id = int(request.GET.get('partner_id'))

274
    m = CagetteMembersSpace()
275

276 277
    limit = int(request.GET.get('limit'))
    offset = int(request.GET.get('offset'))
278 279
    date_from = getattr(settings, 'START_DATE_FOR_SHIFTS_HISTORY', '2018-01-01')
    res["data"] = m.get_shifts_history(partner_id, limit, offset, date_from)
280

281 282 283 284 285 286 287 288 289 290
    return JsonResponse(res)

def offer_extra_shift(request):
    res = {}
    partner_id = int(request.POST['partner_id'])

    m = CagetteMember(partner_id)
    res = m.update_extra_shift_done(0)

    return JsonResponse(res)