Commit 4c1f03cb by Yvon Kerdoncuff

#7345 : remove all code related to extensions/delay

parent 2a6dd52c
...@@ -334,8 +334,7 @@ def manage_makeups(request): ...@@ -334,8 +334,7 @@ def manage_makeups(request):
m = CagetteMembersSpace() m = CagetteMembersSpace()
context = {'title': 'BDM - Rattrapages', context = {'title': 'BDM - Rattrapages',
'module': 'Membres', 'module': 'Membres',
'has_committe_shift': committees_shift_id is not None, 'has_committe_shift': committees_shift_id is not None
'extension_duration': m.get_months_extension_duration()
} }
return HttpResponse(template.render(context, request)) return HttpResponse(template.render(context, request))
...@@ -485,66 +484,6 @@ def update_members_makeups_core(members_data, res = None): ...@@ -485,66 +484,6 @@ def update_members_makeups_core(members_data, res = None):
if res: if res:
res["res"][-1]['standard_points'] = cm.get_member_points("standard") res["res"][-1]['standard_points'] = cm.get_member_points("standard")
def regenerate_member_delay(request):
""" From BDM admin, close existing extension if exists & recreate for 6 months """
res = {}
is_connected_user = CagetteUser.are_credentials_ok(request)
if is_connected_user is True:
raw_data = json.loads(request.body.decode())
# Close extension if has one
member_id = int(raw_data["member_id"])
cm = CagetteMember(member_id)
cm.close_extension()
# Recreate starting now
cs = CagetteShift()
data = {
"idPartner": member_id,
"start_date": date.today().isoformat()
}
duration = raw_data["duration"]
ext_name = "Délai étendue depuis l'admin BDM"
res["create_delay"] = cs.create_delay(data=data, duration=duration, ext_name=ext_name)
if (res["create_delay"]):
try:
# Add 0 pt to counter so odoo updates member status
data = {
'name': "Forcer l'entrée en délai",
'shift_id': False,
'type': "standard",
'partner_id': member_id,
'point_qty': 0
}
cm.update_member_points(data)
data = {
'name': "Forcer l'entrée en délai",
'shift_id': False,
'type': "ftop",
'partner_id': member_id,
'point_qty': 0
}
cm.update_member_points(data)
res["force_entry_delay"] = True
except Exception as e:
print(str(e))
else:
coop_logger.error("regenerate_member_delay: %s, %s", str(res["create_delay"]), str(data))
return HttpResponseServerError()
res["member_data"] = CagetteMembers.get_makeups_members([member_id])[0]
response = JsonResponse(res, safe=False)
else:
res["message"] = "Unauthorized"
response = JsonResponse(res, status=403)
return response
# --- Gestion des créneaux # --- Gestion des créneaux
def delete_shift_registration(request): def delete_shift_registration(request):
......
...@@ -1117,19 +1117,6 @@ class CagetteMember(models.Model): ...@@ -1117,19 +1117,6 @@ class CagetteMember(models.Model):
return res return res
def close_extension(self):
now = datetime.datetime.now().isoformat()
c = [['partner_id', '=', self.id], ['date_start', '<=', now], ['date_stop', '>=', now]]
f = ['id']
res_ids = self.o_api.search_read("shift.extension", c, f)
ids = [d['id'] for d in res_ids]
if ids:
f = {'date_stop': now}
return self.o_api.update('shift.extension', ids, f)
else:
return False
def has_state_unsubscribed_gone_or_associated(self): def has_state_unsubscribed_gone_or_associated(self):
c = [['id', '=', self.id]] c = [['id', '=', self.id]]
......
...@@ -371,52 +371,6 @@ function update_members_makeups(member_ids, action, description) { ...@@ -371,52 +371,6 @@ function update_members_makeups(member_ids, action, description) {
} }
/** /**
* Send request to extend the member's delay, or create one if none open.
* @param {Object} member
*/
function extend_member_delay(member) {
openModal();
let today = new Date();
let today_plus_extension_duration = new Date();
today_plus_extension_duration.setMonth(today_plus_extension_duration.getMonth()+ extension_duration);
const diff_time = Math.abs(today_plus_extension_duration - today);
const diff_days = Math.ceil(diff_time / (1000 * 60 * 60 * 24));
let data = {
member_id: member.id,
duration: diff_days
};
$.ajax({
type: 'POST',
url: "/members/admin/regenerate_member_delay",
data: JSON.stringify(data),
dataType:"json",
traditional: true,
contentType: "application/json; charset=utf-8",
success: function(result) {
let i = makeups_members.findIndex(m => m.id == result.member_data.id);
makeups_members[i].date_delay_stop = result.member_data.date_delay_stop;
display_makeups_members();
closeModal();
},
error: function(data) {
err = {msg: "erreur serveur pour créer un délai", ctx: 'extend_member_delay'};
if (typeof data.responseJSON != 'undefined' && typeof data.responseJSON.error != 'undefined') {
err.msg += ' : ' + data.responseJSON.error;
}
report_JS_error(err, 'members_admin-manage_makeups');
closeModal();
alert('Erreur serveur pour créer un délai. Veuillez contacter le service informatique.');
}
});
}
/**
* Display the members from the search result * Display the members from the search result
*/ */
function display_possible_members() { function display_possible_members() {
......
...@@ -68,7 +68,6 @@ urlpatterns = [ ...@@ -68,7 +68,6 @@ urlpatterns = [
url(r'^delete_shift_template_registration$', admin.delete_shift_template_registration), url(r'^delete_shift_template_registration$', admin.delete_shift_template_registration),
url(r'^shift_subscription$', admin.shift_subscription), url(r'^shift_subscription$', admin.shift_subscription),
url(r'^admin/manage_attached$', admin.manage_attached), url(r'^admin/manage_attached$', admin.manage_attached),
url(r'^admin/regenerate_member_delay$', admin.regenerate_member_delay),
url(r'^admin/manage_attached/create_pair$', admin.create_pair), url(r'^admin/manage_attached/create_pair$', admin.create_pair),
url(r'^admin/manage_attached/delete_pair$', admin.delete_pair), url(r'^admin/manage_attached/delete_pair$', admin.delete_pair),
url(r'^get_makeups_members$', admin.get_makeups_members), url(r'^get_makeups_members$', admin.get_makeups_members),
......
...@@ -27,19 +27,6 @@ class CagetteMembersSpace(models.Model): ...@@ -27,19 +27,6 @@ class CagetteMembersSpace(models.Model):
answer = True answer = True
return answer return answer
def get_months_extension_duration(self):
duration = 2
try:
import re
p = self.o_api.get_system_param('lacagette_membership.extension_duration')
pattern = re.compile(r'([0-9]+) month')
m = pattern.search(p)
if m:
duration = m.group(1)
except Exception as e:
coop_logger.error('get_months_extension_duration : %s', str())
return duration
def get_shifts_history(self, partner_id, limit, offset, date_from): def get_shifts_history(self, partner_id, limit, offset, date_from):
""" Get partner shifts history """ """ Get partner shifts history """
res = [] res = []
......
...@@ -654,18 +654,6 @@ function init_calendar_page() { ...@@ -654,18 +654,6 @@ function init_calendar_page() {
} else if (should_select_makeup() || partner_data.shift_type == 'ftop') { } else if (should_select_makeup() || partner_data.shift_type == 'ftop') {
/* choose a makeup service */ /* choose a makeup service */
// Check if selected new shift is in less than extension end
if (partner_data.date_delay_stop !== 'False') {
date_partner_delay_stop = new Date(partner_data.date_delay_stop);
if (datetime_new_shift > date_partner_delay_stop) {
let msg = `Vous avez jusqu'au ${date_partner_delay_stop.toLocaleDateString("fr-fr", date_options)} ` +
`pour sélectionner un rattrapage (soit une période de ${extension_duration} mois depuis votre absence).`;
alert(msg);
return;
}
}
let modal_template = $("#modal_add_shift_template"); let modal_template = $("#modal_add_shift_template");
modal_template.find(".date_new_shift").text(new_shift_date); modal_template.find(".date_new_shift").text(new_shift_date);
...@@ -853,45 +841,12 @@ function init_shifts_exchange() { ...@@ -853,45 +841,12 @@ function init_shifts_exchange() {
$(this).removeClass('active'); $(this).removeClass('active');
}); });
}); });
} else if (
partner_data.cooperative_state === 'suspended'
&& partner_data.can_have_delay === 'False') {
let msg_template = $("#cant_have_delay_msg_template");
$(".suspended_cant_have_delay_msg").html(msg_template.html());
$("#suspended_cant_have_delay_content").show();
$(".cant_have_delay_form_link")
.show()
.attr('href', member_cant_have_delay_form_link)
.on('click', function() {
setTimeout(500, () => {
$(this).removeClass('active');
});
});
} else if (partner_data.comite === "True") { } else if (partner_data.comite === "True") {
let msg_template = $("#comite_template"); let msg_template = $("#comite_template");
$(".comite_content_msg").html(msg_template.html()); $(".comite_content_msg").html(msg_template.html());
$("#comite_content").show(); $("#comite_content").show();
init_read_only_calendar_page(); init_read_only_calendar_page();
} else if (partner_data.cooperative_state === 'suspended'
&& partner_data.date_delay_stop === 'False') {
$("#suspended_content .makeups_nb").text(partner_data.makeups_to_do);
$("#suspended_content").show();
$(".select_makeups").on('click', () => {
openModal();
// Create 6 month delay
request_delay()
.then(() => {
$("#suspended_content").hide();
$("#shifts_exchange_content").show();
closeModal();
init_calendar_page();
});
});
} else { } else {
$("#shifts_exchange_content").show(); $("#shifts_exchange_content").show();
init_calendar_page(); init_calendar_page();
......
...@@ -131,70 +131,6 @@ function update_content() { ...@@ -131,70 +131,6 @@ function update_content() {
/* - Shifts */ /* - Shifts */
/** /**
* Request a 6 month delay
*/
function request_delay() {
return new Promise((resolve) => {
let today = new Date();
const delay_start = today.getFullYear()+'-'+(today.getMonth()+1)+'-'+today.getDate();
let today_plus_extension_duration = new Date();
today_plus_extension_duration.setMonth(today_plus_extension_duration.getMonth()+ extension_duration);
const diff_time = Math.abs(today_plus_extension_duration - today);
const diff_days = Math.ceil(diff_time / (1000 * 60 * 60 * 24));
$.ajax({
type: 'POST',
url: "/shifts/request_delay",
dataType:"json",
data: {
verif_token: (partner_data.is_associated_people === "True") ? partner_data.parent_verif_token : partner_data.verif_token,
idPartner: partner_data.concerned_partner_id,
start_date: delay_start,
duration: diff_days
},
success: function() {
partner_data.cooperative_state = 'delay';
partner_data.date_delay_stop = today_plus_extension_duration.getFullYear()+'-'+(today_plus_extension_duration.getMonth()+1)+'-'+today_plus_extension_duration.getDate();
resolve();
},
error: function(data) {
if (data.status == 403
&& typeof data.responseJSON != 'undefined'
&& data.responseJSON.message === "delays limit reached") {
closeModal();
let msg_template = $("#cant_have_delay_msg_template");
openModal(
msg_template.html(),
() => {
window.location =member_cant_have_delay_form_link;
},
"J'accède au formulaire",
true,
false
);
} else {
err = {msg: "erreur serveur lors de la création du délai", ctx: 'request_delay'};
if (typeof data.responseJSON != 'undefined' && typeof data.responseJSON.error != 'undefined') {
err.msg += ' : ' + data.responseJSON.error;
}
report_JS_error(err, 'members_space.home');
closeModal();
alert('Erreur lors de la création du délai.');
}
}
});
});
}
/**
* Prepare a shift line to insert into the DOM. * Prepare a shift line to insert into the DOM.
* Is used in: Home - My Shifts tile ; My Shifts - Incoming shifts section * Is used in: Home - My Shifts tile ; My Shifts - Incoming shifts section
* *
...@@ -270,24 +206,9 @@ function init_my_info_data() { ...@@ -270,24 +206,9 @@ function init_my_info_data() {
&& partner_data.cooperative_state !== 'unsubscribed' && partner_data.cooperative_state !== 'unsubscribed'
) { ) {
$(".choose_makeups").show(); $(".choose_makeups").show();
$(".choose_makeups").on('click', () => {
if (
partner_data.cooperative_state === 'suspended'
&& partner_data.date_delay_stop === 'False') {
// If the member is suspended & doesn't have a delay
$(".choose_makeups").on('click', () => {
// Create 6 month delay
request_delay()
.then(() => {
// Then redirect to calendar
goto('echange-de-services');
});
});
} else {
$(".choose_makeups").on('click', () => {
goto('echange-de-services'); goto('echange-de-services');
}); });
}
} }
if (partner_data.extra_shift_done > 0) { if (partner_data.extra_shift_done > 0) {
......
...@@ -102,13 +102,6 @@ def index(request, exception=None): ...@@ -102,13 +102,6 @@ def index(request, exception=None):
md5_calc = hashlib.md5(partnerData['create_date'].encode('utf-8')).hexdigest() md5_calc = hashlib.md5(partnerData['create_date'].encode('utf-8')).hexdigest()
partnerData['verif_token'] = md5_calc 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
# look for parent for associated partner # look for parent for associated partner
if partnerData["parent_id"] is not False: if partnerData["parent_id"] is not False:
partnerData["parent_name"] = partnerData["parent_id"][1] partnerData["parent_name"] = partnerData["parent_id"][1]
...@@ -135,7 +128,6 @@ def index(request, exception=None): ...@@ -135,7 +128,6 @@ def index(request, exception=None):
partnerData["associated_partner_name"] = str(associated_partner["barcode_base"]) + ' - ' + partnerData["associated_partner_name"] partnerData["associated_partner_name"] = str(associated_partner["barcode_base"]) + ' - ' + partnerData["associated_partner_name"]
m = CagetteMembersSpace() m = CagetteMembersSpace()
context['extension_duration'] = m.get_months_extension_duration()
context['show_faq'] = getattr(settings, 'MEMBERS_SPACE_FAQ_TEMPLATE', 'members_space/faq.html') context['show_faq'] = getattr(settings, 'MEMBERS_SPACE_FAQ_TEMPLATE', 'members_space/faq.html')
context['show_abcd_calendar'] = getattr(settings, 'SHOW_ABCD_CALENDAR_TAB', True) context['show_abcd_calendar'] = getattr(settings, 'SHOW_ABCD_CALENDAR_TAB', True)
partnerData["comite"] = m.is_comite(partner_id) partnerData["comite"] = m.is_comite(partner_id)
...@@ -258,7 +250,6 @@ def shifts_exchange(request): ...@@ -258,7 +250,6 @@ def shifts_exchange(request):
context = { context = {
'title': 'Échange de Services', 'title': 'Échange de Services',
'canAddShift': getattr(settings, 'CAN_ADD_SHIFT', False), 'canAddShift': getattr(settings, 'CAN_ADD_SHIFT', False),
'extension_duration': m.get_months_extension_duration()
} }
return HttpResponse(template.render(context, request)) return HttpResponse(template.render(context, request))
......
...@@ -423,87 +423,6 @@ class CagetteShift(models.Model): ...@@ -423,87 +423,6 @@ class CagetteShift(models.Model):
coop_logger.error("Reopen shift : %s", str(e)) coop_logger.error("Reopen shift : %s", str(e))
return response return response
def create_delay(self, data, duration=28, ext_name="Extension créée depuis l'espace membre"):
"""
Create a delay for a member.
If no duration is specified, a delay is by default 28 days from the given start_date.
If the partner already has a current extension: extend it by [duration] days.
Else, create a 28 days delay.
Args:
data
idPartner: int
start_date: string date at iso format (eg. "2019-11-19")
Date from which the delay end date is calculated
(optionnal) extension_beginning: string date at iso format
If specified, will be the actual starting date of the extension.
Should be inferior than start_date.
(at creation only: odoo ignores delays if today's not inside)
duration: nb of days
ext_name: will be displayed in odoo extensions list
"""
action = 'create'
# Get partner extension ids
cond = [['id', '=', data['idPartner']]]
fields = ['extension_ids']
partner_extensions = self.o_api.search_read('res.partner', cond, fields)
response = False
# If has extensions
if 'extension_ids' in partner_extensions[0]:
# Look for current extension: started before today and ends after
current_extension = False
for ext_id in partner_extensions[0]['extension_ids']:
cond = [['id','=',ext_id]]
extension = self.o_api.search_read('shift.extension', cond)
extension = extension[0]
if datetime.datetime.strptime(extension['date_start'], '%Y-%m-%d') <= datetime.datetime.now() and\
datetime.datetime.strptime(extension['date_stop'], '%Y-%m-%d') > datetime.datetime.now():
current_extension = extension
break
# Has a current extension -> Update it
if current_extension != False:
action = 'update'
# Update current extension
if action == 'update':
ext_date_stop = datetime.datetime.strptime(extension['date_stop'], '%Y-%m-%d').date()
ext_new_date_stop = (ext_date_stop + datetime.timedelta(days=duration))
update_data = {
'date_stop': ext_new_date_stop.isoformat()
}
response = self.o_api.update('shift.extension', current_extension['id'], update_data)
# Create the extension
else:
# Get the 'Extension' type id
extension_types = self.o_api.search_read('shift.extension.type')
ext_type_id = getattr(settings, 'EXTENSION_TYPE_ID', 1)
for val in extension_types:
if val['name'] == 'Extension':
ext_type_id = val['id']
starting_date = datetime.datetime.strptime(data['start_date'], '%Y-%m-%d').date()
ending_date = (starting_date + datetime.timedelta(days=duration))
if 'extension_beginning' in data:
starting_date = datetime.datetime.strptime(data['extension_beginning'], '%Y-%m-%d').date()
fields= {
"partner_id": data['idPartner'],
"type_id": ext_type_id,
"date_start": starting_date.isoformat(),
"date_stop": ending_date.isoformat(),
"name": ext_name
}
response = self.o_api.create('shift.extension', fields)
return response
@staticmethod @staticmethod
def reset_members_positive_points(): def reset_members_positive_points():
......
...@@ -12,7 +12,7 @@ var listStates = { ...@@ -12,7 +12,7 @@ var listStates = {
up_to_date:" A jour ", up_to_date:" A jour ",
alert:"Alerte", alert:"Alerte",
exempted:"Exempté", exempted:"Exempté",
delay:"Délai (extension en cours)", delay:"Délai",
suspended:"Suspendu(e)", suspended:"Suspendu(e)",
unsubscribed:"Désinscrit", unsubscribed:"Désinscrit",
unpayed: "Impayé" unpayed: "Impayé"
...@@ -363,52 +363,6 @@ function canAddShift(date_new_shift) { ...@@ -363,52 +363,6 @@ function canAddShift(date_new_shift) {
return answer; return answer;
} }
// Request a delay for the current member, starting at the end of his limit date
// TODO : shift_common
function request_delay() {
openModal(); // Loading on
var formated_limit_date = limitDate.getFullYear()+'-'+(limitDate.getMonth()+1)+'-'+limitDate.getDate();
let delay_data = {
idPartner: dataPartner.partner_id,
verif_token: dataPartner.verif_token,
start_date: formated_limit_date // date when the 28 days delay begins
};
// If not already in delay
if (dataPartner.cooperative_state != 'delay') {
let today = new Date();
var extension_beginning = today.getFullYear()+'-'+(today.getMonth()+1)+'-'+today.getDate();
// set today as the actual starting date for the object delay
// so odoo take account of the delay
delay_data['extension_beginning'] = extension_beginning;
}
$.ajaxSetup({headers: {"X-CSRFToken": getCookie('csrftoken')}});
$.ajax({
type: 'POST',
url: '/shifts/request_delay',
dataType: 'json',
timeout: 3000,
data: delay_data,
success: function(doc) {
closeModal();
alert("L'extension a bien été accordée ! Cette page va se recharger...");
setTimeout( // Due to chrome effect
function() {
document.location.reload();
}
, 500
);
},
error: function() {
alert('Impossible de créer l\'extension. Je dois passer au Bureau des membres pour régler le problème.');
}
});
}
$(document).ready(function() { $(document).ready(function() {
// Retrieve and display partner's shifs // Retrieve and display partner's shifs
loadShiftPartner(dataPartner.partner_id); loadShiftPartner(dataPartner.partner_id);
...@@ -543,29 +497,7 @@ $(document).ready(function() { ...@@ -543,29 +497,7 @@ $(document).ready(function() {
// For partners who can't add a shift as it is // For partners who can't add a shift as it is
if (!can_add_shift) { if (!can_add_shift) {
// Partners who could ask for a delay // Partners who could ask for a delay
if (dataPartner.shift_type == "ftop" || dateShiftNew > limitDate) { if (dataPartner.shift_type != "ftop") {
// Member can ask for 6 delays, which is 24 weeks after entering alert status
// 'date_alert_stop' field is begining of alert + 4 weeks
let date_end_alert = new Date(dataPartner.date_alert_stop);
date_end_alert.setDate(date_end_alert.getDate()+20*7);
// If member can ask for delay
if (new Date() < date_end_alert) {
openModal(
"Pour pouvoir sélectionner un service à partir du <strong>" + limitDate.toLocaleDateString("fr-fr", optDate) + "</strong> je dois demander une extension.<br/>"
+ "Je devrais re-sélectionner ce service dans l'agenda une fois l'extension accordée.",
request_delay,
"Demander une extension"
);
} else {
// can't ask for delays anymore
openModal(
"Je dois sélectionner un service <strong>avant le " + limitDate.toLocaleDateString("fr-fr", optDate) + "</strong>",
closeModal, "J'ai compris"
);
}
} else { // ABCD up-to-date
openModal( openModal(
"Je dois sélectionner un service à échanger.", "Je dois sélectionner un service à échanger.",
closeModal, "J'ai compris" closeModal, "J'ai compris"
......
// Request a delay for the current member
function request_delay() {
//Loading on
openModal();
var today = new Date();
var date = today.getFullYear()+'-'+(today.getMonth()+1)+'-'+today.getDate();
$.ajaxSetup({headers: {"X-CSRFToken": getCookie('csrftoken')}});
$.ajax({
type: 'POST',
url: '/shifts/request_delay',
dataType: 'json',
timeout: 3000,
data: {
idPartner: dataPartner.partner_id,
verif_token: dataPartner.verif_token,
start_date: date
},
success: function(doc) {
document.location.reload();
},
error: function() {
closeModal();
alert('Impossible de créer l\'extension. Je dois passer au Bureau des membres pour régler le problème.');
}
});
}
$(document).ready(function() { $(document).ready(function() {
$('#'+dataPartner.cooperative_state).removeAttr('hidden'); $('#'+dataPartner.cooperative_state).removeAttr('hidden');
......
...@@ -16,6 +16,5 @@ urlpatterns = [ ...@@ -16,6 +16,5 @@ urlpatterns = [
url(r'^affect_shift', views.affect_shift), url(r'^affect_shift', views.affect_shift),
url(r'^add_shift', views.add_shift), url(r'^add_shift', views.add_shift),
url(r'^cancel_shift', views.cancel_shift_case_extra_shift_done), url(r'^cancel_shift', views.cancel_shift_case_extra_shift_done),
url(r'^request_delay', views.request_delay),
url(r'^reset_members_positive_points', views.reset_members_positive_points) url(r'^reset_members_positive_points', views.reset_members_positive_points)
] ]
...@@ -32,12 +32,6 @@ def home(request, partner_id, hashed_date): ...@@ -32,12 +32,6 @@ def home(request, partner_id, hashed_date):
partnerData["leave_start_date"] = listLeave[0]["start_date"] partnerData["leave_start_date"] = listLeave[0]["start_date"]
partnerData["leave_stop_date"] = listLeave[0]["stop_date"] partnerData["leave_stop_date"] = listLeave[0]["stop_date"]
# 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
if partnerData['cooperative_state'] in state_shift_allowed: if partnerData['cooperative_state'] in state_shift_allowed:
# domain = "127.0.0.1" # domain = "127.0.0.1"
...@@ -367,72 +361,6 @@ def cancel_shift_case_extra_shift_done(request): ...@@ -367,72 +361,6 @@ def cancel_shift_case_extra_shift_done(request):
else: else:
return HttpResponseForbidden() return HttpResponseForbidden()
def request_delay(request):
if 'verif_token' in request.POST:
if Verification.verif_token(request.POST.get('verif_token'), int(request.POST.get('idPartner'))) is True:
cs = CagetteShift()
partner_id = int(request.POST['idPartner'])
use_new_members_space = getattr(settings, 'USE_NEW_MEMBERS_SPACE', False)
if use_new_members_space is True:
member_can_have_delay = cs.member_can_have_delay(int(request.POST.get('idPartner')))
if member_can_have_delay is False:
res = { 'message' : 'delays limit reached'}
return JsonResponse(res, status=403)
data = {
"idPartner": partner_id,
"start_date" : request.POST['start_date']
}
if ('extension_beginning' in request.POST):
data['extension_beginning'] = request.POST['extension_beginning']
duration = 28
if ('duration' in request.POST):
duration = int(request.POST['duration'])
response = {'result': False}
try:
new_id = cs.create_delay(data, duration)
if (new_id):
try:
cm = CagetteMember(partner_id)
# Add 0 pt to counter so odoo updates member status
data = {
'name': "Forcer l'entrée en délai",
'shift_id': False,
'type': "standard",
'partner_id': partner_id,
'point_qty': 0
}
cm.update_member_points(data)
data = {
'name': "Forcer l'entrée en délai",
'shift_id': False,
'type': "ftop",
'partner_id': partner_id,
'point_qty': 0
}
cm.update_member_points(data)
except Exception as e:
print(str(e))
response = {'result': True}
else:
coop_logger.error("request delay : %s, %s", str(new_id), str(data))
return HttpResponseServerError()
except Exception as e:
coop_logger.error("request delay : %s, %s", str(e), str(data))
return HttpResponseServerError()
return JsonResponse(response)
else:
return HttpResponseForbidden()
else:
return HttpResponseForbidden()
def reset_members_positive_points(request): def reset_members_positive_points(request):
"""Called by a cron script""" """Called by a cron script"""
return JsonResponse({'res': CagetteShift.reset_members_positive_points()}) return JsonResponse({'res': CagetteShift.reset_members_positive_points()})
......
...@@ -57,13 +57,6 @@ ...@@ -57,13 +57,6 @@
<div id="templates" style="display:none;"> <div id="templates" style="display:none;">
<div id="modal_extend_delay_template">
<p>
Vous vous apprêtez à rallonger le délai de
<span class="member_name"></span>
pour une durée de {{extension_duration}} mois à partir d'aujourd'hui.
</p>
</div>
<div id="modal_incr_makeup_counter"> <div id="modal_incr_makeup_counter">
<p>Ajouter un rattrapage à <span class="member_name"></span> ?</p> <p>Ajouter un rattrapage à <span class="member_name"></span> ?</p>
<br><label for="incr-explanation">Explication : </label><input class="" type="text" id="incr-explanation"> <br><label for="incr-explanation">Explication : </label><input class="" type="text" id="incr-explanation">
...@@ -86,6 +79,5 @@ ...@@ -86,6 +79,5 @@
<script src='{% static "js/admin/manage_makeups.js" %}?v=1651853225'></script> <script src='{% static "js/admin/manage_makeups.js" %}?v=1651853225'></script>
<script> <script>
var has_committe_shift = '{{has_committe_shift}}' var has_committe_shift = '{{has_committe_shift}}'
const extension_duration = {{extension_duration}};
</script> </script>
{% endblock %} {% endblock %}
...@@ -220,10 +220,7 @@ ...@@ -220,10 +220,7 @@
Votre compteur est dorénavant à <span class="points"></span> point(s).<br /> Votre compteur est dorénavant à <span class="points"></span> point(s).<br />
<div class="explanations"> <div class="explanations">
Pour pouvoir faire vos courses, votre compteur doit être au moins à -1 point. <br /> Pour pouvoir faire vos courses, vous devez avoir choisi une date pour tous vos rattrapages, si vous en avez.
Dans le cas où vous n’avez pas le temps de faire votre rattrapage, vous pouvez demander une extension.
<br />
Une extension vous donne 4 semaines de plus pour faire votre rattrapage.
</div> </div>
</div> </div>
Votre prochain service <span class="service_verb">est prévu</span> le <span class="next_shift"></span> Votre prochain service <span class="service_verb">est prévu</span> le <span class="next_shift"></span>
......
...@@ -95,12 +95,6 @@ ...@@ -95,12 +95,6 @@
<p>3/12 <i class="arrow_explanation_numbers fas fa-arrow-right"></i> il y a déjà 3 places réservées à ce service sur 12 disponibles. <p>3/12 <i class="arrow_explanation_numbers fas fa-arrow-right"></i> il y a déjà 3 places réservées à ce service sur 12 disponibles.
<b>Plus le chiffre de gauche est petit, plus on a besoin de coopérateurs.rices à ce service !</b></p> <b>Plus le chiffre de gauche est petit, plus on a besoin de coopérateurs.rices à ce service !</b></p>
</div> </div>
<div id="cant_have_delay_msg_template">
<h3>Bonjour, tu avais {{extension_duration}} mois pour rattraper tes services manqués et il semblerait que tu ne l'aies pas fait.</h3>
<h3>Tu ne peux plus sélectionner de rattrapages sur ton espace membre pour le moment,
merci de contacter le bureau des membres pour résoudre ce problème en remplissant ce formulaire : </h3>
</div>
<div id="comite_template"> <div id="comite_template">
<h3>Vous êtes inscrit.e dans le service des comités, vous n'avez pas accès au calendrier d'échange des services car vous vous organisez directement avec le responsable du comité. Si vous avez des rattrapages à réaliser, merci de contacter le responsable du comité qui vous aidera à planifier les rattrapages ou trouver une solution.</h3> <h3>Vous êtes inscrit.e dans le service des comités, vous n'avez pas accès au calendrier d'échange des services car vous vous organisez directement avec le responsable du comité. Si vous avez des rattrapages à réaliser, merci de contacter le responsable du comité qui vous aidera à planifier les rattrapages ou trouver une solution.</h3>
<h3>Le calendrier ci-dessous est en lecture seule</h3> <h3>Le calendrier ci-dessous est en lecture seule</h3>
...@@ -173,7 +167,6 @@ ...@@ -173,7 +167,6 @@
var block_actions_for_attached_people = '{{block_actions_for_attached_people}}'; var block_actions_for_attached_people = '{{block_actions_for_attached_people}}';
var block_service_exchange_24h_before = '{{block_service_exchange_24h_before}}'; var block_service_exchange_24h_before = '{{block_service_exchange_24h_before}}';
const canAddShift = {{canAddShift}}; const canAddShift = {{canAddShift}};
const extension_duration = {{extension_duration}};
const not_allowed_shift_op = `{{not_allowed_shift_op|safe}}`; const not_allowed_shift_op = `{{not_allowed_shift_op|safe}}`;
</script> </script>
<script src="{% static "js/all_common.js" %}?v=1651853225"></script> <script src="{% static "js/all_common.js" %}?v=1651853225"></script>
......
...@@ -18,7 +18,6 @@ ...@@ -18,7 +18,6 @@
<div id="suspended_content" class="shifts_exchange_page_content"> <div id="suspended_content" class="shifts_exchange_page_content">
<h3> <h3>
J'ai <span class="makeups_nb"></span> rattrapage(s) à effectuer, je dois le(s) sélectionner pour pouvoir refaire mes courses. J'ai <span class="makeups_nb"></span> rattrapage(s) à effectuer, je dois le(s) sélectionner pour pouvoir refaire mes courses.
J'ai {{extension_duration}} mois de délai pour le(s) rattraper.
</h3> </h3>
<h3> <h3>
Si besoin, je peux contacter le Bureau des membres via la rubrique "J'ai une demande" pour expliquer ma situation. Si besoin, je peux contacter le Bureau des membres via la rubrique "J'ai une demande" pour expliquer ma situation.
......
...@@ -25,33 +25,15 @@ ...@@ -25,33 +25,15 @@
<div> <div>
<div id="suspended" hidden> <div id="suspended" hidden>
<h2>Bonjour. Il semblerait que vous soyez « suspendu.e ».</h2> <h2>Bonjour. Il semblerait que vous soyez « suspendu.e ».</h2>
<div id="delay" hidden> <p>Pour pouvoir faire vos courses, vous devez positionner vos rattrapages depuis le calendrier d'échances de services.</p>
<p>Ça veut dire que soit :</p> <p>Vous passerez alors en "délai" jusqu'à ce que vos rattrapages soient faits.</p>
<ul>
<li>vous avez raté deux services. Lorsque votre compteur passe à -2, vous êtes immédiatement suspendus,</li>
<li>vous avez raté un service et vous ne l'avez pas rattrapé dans les 4 semaines qui ont suivis,</li>
<li>vous avez été désinscrit.e pour avoir raté 3 services et venez d'être réinscrit.e.</li>
</ul>
<p>Heureusement, vous pouvez demander un délai !</p>
<p>Cela vous donne quatre semaines supplémentaires pour rattraper le service manqué (ou les deux services manqués).Vous pouvez demander jusqu'à 6 délais d'affilé.</p>
<p>En pratique, ça signifie que vous avez jusqu'à 24 semaines pour rattraper un service raté !</p>
<p>Si vous ratez un troisième service, vous serez désinscrit.e, vous n'aurez plus accès au magasin et votre place sera libérée pour un.e autre membre.</p>
<br/>
<p> <p>
{% if partnerData.is_leave %} {% if partnerData.is_leave %}
<strong> <strong>
Mais, vous êtes actuellement en période de congé. <br/> Mais, vous êtes actuellement en période de congé. <br/>
Merci de passer au magasin pour régulariser la situation. Merci de passer au magasin pour régulariser la situation.
</strong> </strong>
{% else %}
Vous pouvez demander un délai en cliquant ici : <a class='btn--primary' onclick="request_delay()">Demander un délai</a>
{% endif %} {% endif %}
</p>
</div>
<div id="no_delay" hidden>
<p>Vous ne pouvez plus demander de délai, merci de passer au magasin pour vous régulariser.</p>
</div>
<p>
</div> </div>
<div id="unsubscribed" hidden> <div id="unsubscribed" hidden>
{% if UNSUBSCRIBED_MSG %} {% if UNSUBSCRIBED_MSG %}
......
...@@ -141,16 +141,6 @@ ...@@ -141,16 +141,6 @@
</p> </p>
{% endif %} {% endif %}
{% if data.date_alert_stop %}
<p>
En alerte jusqu'au {{ data.date_alert_stop|date:"d F Y" }}
</p>
{% endif %}
{% if data.date_delay_stop %}
<p>
Extension accordée jusqu'au {{ data.date_delay_stop|date:"d F Y" }}
</p>
{% endif %}
{% endif %} {% endif %}
{% endif %} {% endif %}
</div> </div>
......
...@@ -85,12 +85,6 @@ def index(request): ...@@ -85,12 +85,6 @@ def index(request):
md5_calc = hashlib.md5(partnerData['create_date'].encode('utf-8')).hexdigest() md5_calc = hashlib.md5(partnerData['create_date'].encode('utf-8')).hexdigest()
partnerData['verif_token'] = md5_calc partnerData['verif_token'] = md5_calc
# coop_logger.info(partnerData) # coop_logger.info(partnerData)
# 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
# Following part is a copy of shifts/views.py (def home) # Following part is a copy of shifts/views.py (def home)
context['partnerData'] = partnerData context['partnerData'] = partnerData
days_to_hide = "0" days_to_hide = "0"
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment