views.py 16.3 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 105 106 107 108 109 110 111
        if 'create_date' in partnerData:
            md5_calc = hashlib.md5(partnerData['create_date'].encode('utf-8')).hexdigest()
            partnerData['verif_token'] = md5_calc

            # Error case encountered from Odoo: member in delay state and last extension is over -> member is suspended
            try:
                if partnerData['cooperative_state'] == "delay" and datetime.datetime.strptime(partnerData['date_delay_stop'], '%Y-%m-%d') < datetime.datetime.now():
                    partnerData['cooperative_state'] = "suspended"
            except:
                pass

112
            # look for parent for associated partner
113 114 115
            if partnerData["parent_id"] is not False:
                partnerData["parent_name"] = partnerData["parent_id"][1]
                partnerData["parent_id"] = partnerData["parent_id"][0]
Félicie committed
116 117
                md5_calc = hashlib.md5(partnerData['parent_create_date'].encode('utf-8')).hexdigest()
                partnerData['parent_verif_token'] = md5_calc
118 119 120
                partnerData['makeups_to_do'] = partnerData['parent_makeups_to_do']
                partnerData['date_delay_stop'] = partnerData['parent_date_delay_stop']
                partnerData['can_have_delay'] = cs.member_can_have_delay(int(partnerData["parent_id"]))
121
                partnerData['extra_shift_done'] = partnerData["parent_extra_shift_done"]
Félicie committed
122

123 124
            else:
                partnerData["parent_name"] = False
125
                partnerData['can_have_delay'] = cs.member_can_have_delay(int(partner_id))
126

127 128 129 130 131 132 133 134 135 136
            # 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"]

137
            m = CagetteMembersSpace()
138
            context['extension_duration'] = m.get_months_extension_duration()
139
            context['show_faq'] = getattr(settings, 'MEMBERS_SPACE_FAQ_TEMPLATE', 'members_space/faq.html')
140
            context['show_abcd_calendar'] = getattr(settings, 'SHOW_ABCD_CALENDAR_TAB', True)
141 142
            partnerData["comite"] = m.is_comite(partner_id)

143 144
            context['partnerData'] = partnerData

145 146
            context['mag_name'] = getattr(settings, 'MAG_NAME', '')

147 148
            # Days to hide in the calendar
            days_to_hide = "0"
149 150
            context['SHIFTS_MOVING_ALLOWED'] = getattr(settings, 'SHIFTS_MOVING_ALLOWED', '')
            context['ALLOW_FTOP_TO_DELETE_SHIFT'] = getattr(settings, 'ALLOW_FTOP_TO_DELETE_SHIFT', False)
151 152 153 154
            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
155 156 157 158 159
            # 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)

160 161
            can_add_shift = getattr(settings, 'CAN_ADD_SHIFT', False)
            context['canAddShift'] = "true" if can_add_shift is True else "false"
162 163

            msettings = MConfig.get_settings('members')
164
            context['forms_link'] = msettings['forms_link']['value'] if 'forms_link' in msettings else ''
165 166 167 168 169 170 171 172 173
            context['unsuscribe_form_link'] = ( msettings['unsuscribe_form_link']['value'] 
                if 'unsuscribe_form_link' in msettings 
                else '')
            context['member_cant_have_delay_form_link'] = ( msettings['member_cant_have_delay_form_link']['value'] 
                if 'member_cant_have_delay_form_link' in msettings 
                else '')
            context['abcd_calendar_link'] = ( msettings['abcd_calendar_link']['value'] 
                if 'abcd_calendar_link' in msettings 
                else '')
174 175 176 177 178 179 180 181 182 183 184 185 186 187
            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 ''
188
            context['on_picking_shift_template_msg'] = msettings['on_picking_shift_template_msg']['value'] if 'on_picking_shift_template_msg' in msettings else ''
189 190 191 192 193 194 195 196
            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
197 198 199 200 201 202
        else:
            # may arrive when switching database without cleaning cookie
            return redirect('/website/deconnect')

    return _get_response_according_to_credentials(request, credentials, context, template)

203
def home(request):
204 205 206 207 208 209
    """ 
        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
    """
210
    template = loader.get_template(getattr(settings, 'MEMBERS_SPACE_HOME_TEMPLATE', 'members_space/home.html'))
211 212 213 214 215 216 217 218 219
    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
220 221 222
        if getattr(settings, 'ASSOCIATE_PEOPLE_CAN_CHANGE_SHIFT_TEMPLE_REGISTRATION', False) is False:
            if partnerData['is_associated_people'] is True:
                coop_can_change_shift_template = False
223 224
    context = {
        'title': 'Espace Membres',
225
        'coop_can_change_shift_template': coop_can_change_shift_template,
226
        'max_begin_hour': settings.MAX_BEGIN_HOUR,
227
    }
228 229 230 231 232 233
    # 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']
234 235
    return HttpResponse(template.render(context, request))

236
def my_info(request):
237
    """ Endpoint the front-end will call to load the "My info" page. """
238
    template = loader.get_template('members_space/my_info.html')
239 240
    context = {
        'title': 'Mes Infos',
241 242
        '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")
243 244 245 246
    }
    return HttpResponse(template.render(context, request))

def my_shifts(request):
247
    """ Endpoint the front-end will call to load the "My shifts" page. """
248
    template = loader.get_template('members_space/my_shifts.html')
249 250 251 252 253 254
    context = {
        'title': 'Mes Services',
    }
    return HttpResponse(template.render(context, request))

def shifts_exchange(request):
255
    """ Endpoint the front-end will call to load the "Shifts exchange" page. """
256
    template = loader.get_template('members_space/shifts_exchange.html')
257
    m = CagetteMembersSpace()
258 259
    context = {
        'title': 'Échange de Services',
260
        'canAddShift': getattr(settings, 'CAN_ADD_SHIFT', False),
261
        'extension_duration': m.get_months_extension_duration()
262 263 264
    }
    return HttpResponse(template.render(context, request))

Etienne Freiss committed
265
def faqBDM(request):
266 267 268 269 270 271
    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',
272
            'MEMBERS_GUIDE_URL': getattr(settings, 'MEMBERS_GUIDE_URL', None)
273 274 275 276
        }
        content = template.render(context, request)

    return HttpResponse(content)
277

278
def no_content(request):
279
    """ Endpoint the front-end will call to load the "No content" page. """
280
    template = loader.get_template('members_space/no_content.html')
281 282
    context = {
        'title': 'Contenu non trouvé',
283
    }
284 285
    return HttpResponse(template.render(context, request))

286
def get_shifts_history(request):
287 288 289
    res = {}
    partner_id = int(request.GET.get('partner_id'))

290
    m = CagetteMembersSpace()
291

292 293
    limit = int(request.GET.get('limit'))
    offset = int(request.GET.get('offset'))
294 295
    date_from = getattr(settings, 'START_DATE_FOR_SHIFTS_HISTORY', '2018-01-01')
    res["data"] = m.get_shifts_history(partner_id, limit, offset, date_from)
296

297 298 299 300 301 302 303 304 305 306
    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)