From b5da0a74ea6a7aae543af50b02f255e5c59cb9ed Mon Sep 17 00:00:00 2001
From: Nicolas ROCHE <nroche@entrouvert.com>
Date: Wed, 23 Dec 2020 15:18:51 +0100
Subject: [PATCH 2/4] maelis: allow school year computation from a given date
 (#48480)

---
 passerelle/apps/maelis/models.py |  6 +++---
 passerelle/apps/maelis/utils.py  | 11 ++++++-----
 tests/test_maelis.py             | 12 ++++++++++++
 3 files changed, 21 insertions(+), 8 deletions(-)

diff --git a/passerelle/apps/maelis/models.py b/passerelle/apps/maelis/models.py
index 617f69ed..273e1a47 100644
--- a/passerelle/apps/maelis/models.py
+++ b/passerelle/apps/maelis/models.py
@@ -132,17 +132,17 @@ class Maelis(BaseResource):
         try:
             return self.link_set.get(name_id=name_id)
         except Link.DoesNotExist:
             raise APIError('User not linked to family', err_code='not-found')
 
     def get_family_data(self, family_id, school_year=None):
         if not school_year:
             # fallback to current year if not provided
-            school_year = utils.get_default_school_year()
+            school_year = utils.get_school_year()
         family_data = serialize_object(self.call('FamilyService?wsdl',
                                                  'readFamily',
                                                  dossierNumber=family_id,
                                                  schoolYear=school_year))
         for child in family_data['childInfoList']:
             utils.normalize_person(child)
         return family_data
 
@@ -165,17 +165,17 @@ class Maelis(BaseResource):
                 'schema': {
                     'application/json': LINK_SCHEMA
                 }
             }
         })
     def link(self, request, NameID, post_data):
         if 'school_year' not in post_data:
             # fallback to default year if not provided
-            post_data['school_year'] = utils.get_default_school_year()
+            post_data['school_year'] = utils.get_school_year()
         r = self.call('FamilyService?wsdl', 'readFamilyByPassword',
                       dossierNumber=post_data['family_id'],
                       password=post_data['password'],
                       schoolYear=post_data['school_year']
                       )
         if not r.number:
             raise APIError('Family not found', err_code='not-found')
         Link.objects.update_or_create(resource=self, name_id=NameID,
@@ -380,17 +380,17 @@ class Maelis(BaseResource):
         })
     def activity_list(self, request, NameID, personID, school_year=None, start_datetime=None,
                       end_datetime=None):
         link = self.get_link(NameID)
         family_data = self.get_family_data(link.family_id)
         if personID not in [c['id'] for c in family_data['childInfoList']]:
             raise APIError('Child not found', err_code='not-found')
         if not school_year:
-            school_year = utils.get_default_school_year()
+            school_year = utils.get_school_year()
         if not start_datetime:
             start_datetime = timezone.now()
         if not end_datetime:
             end_datetime = start_datetime + timezone.timedelta(days=62)
         r = self.call('ActivityService?wsdl', 'readActivityList',
                       schoolyear=school_year, numPerson=personID,
                       dateStartCalend=start_datetime,
                       dateEndCalend=end_datetime)
diff --git a/passerelle/apps/maelis/utils.py b/passerelle/apps/maelis/utils.py
index 4b29d0c8..a187d157 100644
--- a/passerelle/apps/maelis/utils.py
+++ b/passerelle/apps/maelis/utils.py
@@ -54,14 +54,15 @@ def normalize_activity(activity):
 
 def normalize_person(person):
     person['id'] = person['num']
     person['text'] = '{} {}'.format(
                 person['firstname'], person['lastname']).strip()
     return person
 
 
-def get_default_school_year():
-    now = timezone.now()
-    if now.strftime('%m-%d') >= '07-31':
-        return now.year
+def get_school_year(date=None):
+    if not date:
+        date = timezone.now().date()
+    if date.strftime('%m-%d') >= '07-31':
+        return date.year
     else:
-        return now.year - 1
+        return date.year - 1
diff --git a/tests/test_maelis.py b/tests/test_maelis.py
index 5790046b..b7f1445d 100644
--- a/tests/test_maelis.py
+++ b/tests/test_maelis.py
@@ -1,15 +1,18 @@
 # -*- coding: utf-8 -*-
 
 import mock
 import os
 import pytest
 
+from django.utils.dateparse import parse_date
+
 from passerelle.apps.maelis.models import Maelis, Link
+from passerelle.apps.maelis.utils import get_school_year
 
 from passerelle.utils.jsonresponse import APIError
 
 import utils
 
 pytestmark = pytest.mark.django_db
 
 
@@ -193,8 +196,17 @@ def test_get_invoice_details(mocked_post, mocked_get, invoice_service_wsdl,
                                          status_code=200,
                                          headers={'Content-Type': 'text/xml'}
                                          )
     Link.objects.create(resource=connector, family_id='3264', name_id='local')
     resp = app.get('/maelis/test/regie/1/invoice/3264-53186?NameID=local')
     assert resp.json['data']
     assert resp.json['data']['label'] == 'FACTURATION SEPTEMBRE 2014'
     assert resp.json['data']['display_id'] == '53186'
+
+
+@pytest.mark.parametrize('date, schoolyear', [
+    ('2020-07-30', 2019),
+    ('2020-07-31', 2020),
+])
+def test_get_school_year(date, schoolyear):
+    date = parse_date(date)
+    assert schoolyear == get_school_year(date)
-- 
2.29.2

