Skip to content

Commit

Permalink
issue santropolroulant#52 Specify upcoming dates where the client has…
Browse files Browse the repository at this point in the history
… chosen not to receive any meal
  • Loading branch information
rlouhibi-outbox authored and guillaumep committed Feb 19, 2021
1 parent dcc1cb3 commit 4cea62f
Show file tree
Hide file tree
Showing 10 changed files with 157 additions and 3 deletions.
21 changes: 21 additions & 0 deletions souschef/frontend/js/meal-cancellation.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
$(function() {

// Javascript of the meal cancellation.
// **************************************

var config = {
dateFormat: "yy-mm-dd",
separator: "|"
};

$('#id_cancel_meal_dates').hide();
$('#cancel_meal_dates').multiDatesPicker(config);
if($('#id_cancel_meal_dates').val()){
$('#cancel_meal_dates').multiDatesPicker('addDates', JSON.parse($('#id_cancel_meal_dates').val()));

}
$('#cancel_meal_dates').bind('DOMSubtreeModified', function(){
var dates = $('#cancel_meal_dates').multiDatesPicker('getDates');
$('#id_cancel_meal_dates').val(JSON.stringify(dates));
});
});
4 changes: 4 additions & 0 deletions souschef/frontend/scss/base/multidatespicker.scss
Original file line number Diff line number Diff line change
Expand Up @@ -17,3 +17,7 @@
color: white; /* a color that is readeable with the color above */
}
/* end: jQuery UI Datepicker emphasis on selected dates */

#cancel_meal_dates>.ui-datepicker .ui-datepicker-calendar .ui-state-highlight a {
background: red;
}
18 changes: 18 additions & 0 deletions souschef/member/forms.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
from datetime import datetime
import json

from django import forms
from django.core.exceptions import ObjectDoesNotExist
from django.utils import timezone
Expand Down Expand Up @@ -245,6 +248,11 @@ def __init__(self, *args, **kwargs):
)
)

cancel_meal_dates = forms.CharField(
required=False,
label=_('Cancel dates'),
)

def clean(self):
"""
The meal defaults are required for the scheduled delivery days:
Expand All @@ -256,6 +264,16 @@ def clean(self):
"""
super(ClientRestrictionsInformation, self).clean()

def to_cancel_date(str_date):
return datetime.strptime(
str_date, "%Y-%m-%d"
).date()

if self.cleaned_data.get('cancel_meal_dates'):
self.cleaned_data['cancel_meal_dates'] = list(map(to_cancel_date,
json.loads(self.cleaned_data['cancel_meal_dates'])))


if self.cleaned_data.get('delivery_type') == 'O':
# Ongoing
meals_schedule = self.cleaned_data.get('meals_schedule')
Expand Down
25 changes: 25 additions & 0 deletions souschef/member/migrations/0037_meal_cancelation.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
# -*- coding: utf-8 -*-
# Generated by Django 1.11.29 on 2021-02-19 18:43
from __future__ import unicode_literals

from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone


class Migration(migrations.Migration):

dependencies = [
('member', '0036_member_addresses'),
]

operations = [
migrations.CreateModel(
name='Client_cancel_meal_date',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('cancel_date', models.DateField(default=django.utils.timezone.now)),
('client', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='cancel_meal_dates', to='member.Client', verbose_name='client')),
],
),
]
22 changes: 22 additions & 0 deletions souschef/member/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -1106,3 +1106,25 @@ def __str__(self):
return "{} {} <has> {}".format(self.client.member.firstname,
self.client.member.lastname,
self.component.name)


class Client_cancel_meal_date(models.Model):
client = models.ForeignKey(
'member.Client',
verbose_name=_('client'),
on_delete=models.CASCADE,
related_name='cancel_meal_dates'
)

cancel_date = models.DateField(
auto_now=False,
auto_now_add=False,
default=timezone.now,
null=False
)


def __str__(self):
return "{} {} <has a cancel date> {}".format(self.client.member.firstname,
self.client.member.lastname,
self.cancel_date)
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
{% load i18n %}
{% load static %}
<h4 class="ui dividing header">{% trans 'Meal status' %}</h4>

<div class="field">
Expand Down Expand Up @@ -54,3 +55,9 @@ <h4 class="ui dividing header">{% trans 'Food preferences' %}</h4>
<label>{{ form.dish_to_avoid.label }}</label>
{{ form.dish_to_avoid }}
</div>

<h4 class="ui dividing header">{% trans 'Meal cancelation' %}</h4>
<div class="field">
<div id="cancel_meal_dates"></div>
{{ form.cancel_meal_dates }}
</div>
13 changes: 13 additions & 0 deletions souschef/member/templates/client/update/base.html
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,9 @@
{% load leaflet_tags %}
{% leaflet_js %}
{% leaflet_css %}
<link href="https://code.jquery.com/ui/1.12.1/themes/smoothness/jquery-ui.css" rel="stylesheet">
{% comment %} Wash out jquery UI css on other semantic UI elements by importing it again. {% endcomment %}
<link href="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.2.11/semantic.min.css" rel="stylesheet">
{% endblock %}

{% block title %}
Expand Down Expand Up @@ -76,4 +79,14 @@ <h1 class="ui header">
{% else %}
<script src="{% static 'js/leaflet.min.js' %}" type="application/javascript"></script>
{% endif %}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.1/jquery-ui.min.js" type="application/javascript"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.1/i18n/jquery-ui-i18n.min.js" type="application/javascript"></script>
<script type="application/javascript">
$.datepicker.setDefaults( $.datepicker.regional[ "{{ LANGUAGE_CODE }}" ] );
</script>
{% if debug %}
<script src="{% static 'js/meal-cancellation.js' %}" type="application/javascript"></script>
{% else %}
<script src="{% static 'js/meal-cancellation.min.js' %}" type="application/javascript"></script>
{% endif %}
{% endblock %}
23 changes: 22 additions & 1 deletion souschef/member/views.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
# coding: utf-8

import csv
import json

from datetime import datetime

from django.contrib import messages
from django.contrib.auth.mixins import LoginRequiredMixin
Expand Down Expand Up @@ -45,6 +48,7 @@
DAYS_OF_WEEK,
Client_avoid_ingredient,
Client_avoid_component,
Client_cancel_meal_date,
HOME, WORK, CELL, EMAIL)
from souschef.order.mixins import FormValidAjaxableResponseMixin
from souschef.order.models import SIZE_CHOICES, Order
Expand Down Expand Up @@ -224,6 +228,7 @@ def save(self, id=None):
'payment_information'].cleaned_data
dietary_restriction = self.form_dict[
'dietary_restriction'].cleaned_data


member, created = Member.objects.update_or_create(
id=id,
Expand Down Expand Up @@ -407,7 +412,8 @@ def save_preferences(self, client):
Client_avoid_component.objects.create(
client=client,
component=component_to_avoid
)
)


def billing_member_is_member(self):
basic_information = self.form_dict['basic_information']
Expand Down Expand Up @@ -896,6 +902,11 @@ def get_initial(self):
client = get_object_or_404(
Client, pk=self.kwargs.get('pk')
)
cancel_meal_dates = [datetime.combine(date_entry.cancel_date, datetime.min.time()).strftime("%Y-%m-%d")
for date_entry
in client.cancel_meal_dates.all()]
cancel_meal_dates_json = json.dumps(cancel_meal_dates)

initial.update({
'status': True if client.status == Client.ACTIVE else False,
'delivery_type': client.delivery_type,
Expand All @@ -904,6 +915,7 @@ def get_initial(self):
'ingredient_to_avoid': client.ingredients_to_avoid.all,
'dish_to_avoid': client.components_to_avoid.all,
'food_preparation': client.food_preparation.all,
'cancel_meal_dates': cancel_meal_dates_json,
})
for k, v in (client.meal_default_week or {}).items():
initial[k] = v
Expand Down Expand Up @@ -953,6 +965,15 @@ def save(self, form, client):
component=component_to_avoid
)

# Save cancel meal dates
client.cancel_meal_dates.all().delete()
cancel_meal_dates = form['cancel_meal_dates']
for cancel_meal_date in cancel_meal_dates:
Client_cancel_meal_date.objects.create(
client=client,
cancel_date=cancel_meal_date
)

# Save preferences
json = {}
for days, v in DAYS_OF_WEEK:
Expand Down
3 changes: 3 additions & 0 deletions souschef/order/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -158,6 +158,9 @@ def auto_create_orders(self, delivery_date, clients):
weekday = delivery_date.weekday() # Monday is 0, Sunday is 6
day = DAYS_OF_WEEK[weekday][0] # 0 -> 'monday', 6 -> 'sunday'
for client in clients:
is_cancel = client.cancel_meal_dates.filter(cancel_date=delivery_date)
if is_cancel:
continue
try:
order = Order.objects.get(client=client,
delivery_date=delivery_date)
Expand Down
24 changes: 22 additions & 2 deletions tools/gulp/gulpfile.js
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,14 @@ const sources = {
site: [
`${SRC_JS}/multidatespicker.js`,
]
},
mealCancellation: {
vendor: [
'node_modules/jquery-ui-multi-date-picker/dist/jquery-ui.multidatespicker.js',
],
site: [
`${SRC_JS}/meal-cancellation.js`,
]
}
},

Expand Down Expand Up @@ -161,6 +169,17 @@ gulp.task('scripts-multidatespicker', () =>
.pipe(gulp.dest(destinations.js))
);

gulp.task('scripts-meal-cancellation', () =>
gulp.src([].concat(sources.js.mealCancellation.vendor).concat(sources.js.mealCancellation.site))
.pipe(concat('meal-cancellation.js'))
.pipe(gulp.dest(destinations.js))
.pipe(bytediff.start())
.pipe(uglify())
.pipe(bytediff.stop(bytediffFormatter))
.pipe(rename({ suffix: '.min' }))
.pipe(gulp.dest(destinations.js))
);

gulp.task('images', () =>
gulp.src([].concat(sources.img.vendor).concat(sources.img.site))
.pipe(cache(imagemin({
Expand All @@ -177,13 +196,13 @@ gulp.task('fonts', () =>
);

gulp.task('default', () => {
gulp.start('styles', 'scripts-multidatespicker', 'scripts-leaflet', 'scripts',
gulp.start('styles', 'scripts-multidatespicker', 'scripts-leaflet', 'scripts', 'scripts-meal-cancellation',
'images', 'fonts');
});

gulp.task('watch', ['default'], () => {
gulp.watch(`${SRC_SCSS}/**/*.scss`, ['styles']);
gulp.watch(`${SRC_JS}/**/*.js`, ['scripts-multidatespicker', 'scripts-leaflet', 'scripts']);
gulp.watch(`${SRC_JS}/**/*.js`, ['scripts-multidatespicker', 'scripts-leaflet', 'scripts', 'scripts-meal-cancellation']);
gulp.watch(`${SRC_IMG}/**/*`, ['images']);
});

Expand All @@ -192,6 +211,7 @@ gulp.task('validate', () =>
.concat(sources.js.scripts.site)
.concat(sources.js.leaflet.site)
.concat(sources.js.multiDatesPicker.site)
.concat(sources.js.mealCancellation.site)
)
.pipe(debug())
.pipe(validate())
Expand Down

0 comments on commit 4cea62f

Please sign in to comment.