From 4c3ad9826227ca82f2c34ad855441d6ba98aa937 Mon Sep 17 00:00:00 2001
From: Emmanuel Cazenave <ecazenave@entrouvert.com>
Date: Thu, 9 Apr 2020 15:34:26 +0200
Subject: [PATCH 2/2] atal: add 'new-comments' endpoint (#41533)

---
 passerelle/apps/atal/models.py | 55 +++++++++++++++++++++++++++++++++-
 tests/test_atal.py             | 51 +++++++++++++++++++++++++++++++
 2 files changed, 105 insertions(+), 1 deletion(-)

diff --git a/passerelle/apps/atal/models.py b/passerelle/apps/atal/models.py
index 1cc71440..33961971 100644
--- a/passerelle/apps/atal/models.py
+++ b/passerelle/apps/atal/models.py
@@ -18,7 +18,7 @@ import base64
 import binascii
 
 from django.db import models
-from django.utils import dateformat
+from django.utils import dateformat, dateparse
 from django.utils.encoding import force_text
 from django.utils.six.moves import urllib
 from django.utils.translation import ugettext_lazy as _
@@ -305,3 +305,56 @@ class ATALConnector(BaseResource):
             **data
         )
         return {}
+
+    @endpoint(
+        methods=['get'], perm='can_access', example_pattern='{demande_number}/',
+        pattern='^(?P<demande_number>\w+)/$', name='new-comments',
+        parameters={
+            'demande_number': DEMANDE_NUMBER_PARAM,
+        }
+    )
+    def new_comments(self, request, demande_number, last_datetime):
+
+        def issup(datetime1, datetime2):
+            if datetime1.tzinfo is None or datetime2.tzinfo is None:
+                datetime1 = datetime1.replace(tzinfo=None)
+                datetime2 = datetime2.replace(tzinfo=None)
+            return datetime1 > datetime2
+
+        last_datetime = dateparse.parse_datetime(last_datetime)
+        if last_datetime is None:
+            raise APIError('Wrong datetime format')
+
+        demand_details = helpers.serialize_object(
+            self._soap_call(
+                wsdl='DemandeService', method='retrieveDetailsDemande',
+                demandeNumberParam=demande_number)
+        )
+        if not demand_details:
+            raise APIError('Could not get comments')
+
+        new_comments, all_comments = [], []
+        responses = (demand_details.get('reponses') or {}).get('Reponse') or []
+        if responses:
+            for response in responses:
+                comment = {
+                    'text': response.get('commentaires'),
+                    'date': None,
+                    'date_raw': None
+                }
+                dateobj = None
+                if 'dateReponse' in response:
+                    dateobj = response['dateReponse']
+                    comment['date'] = dateformat.format(dateobj, DATE_FORMAT)
+                    comment['date_raw'] = dateformat.format(dateobj, 'c')
+
+                all_comments.append(comment)
+                if dateobj and issup(dateobj, last_datetime):
+                    new_comments.append(comment)
+
+        return {
+            'data': {
+                'new_comments': new_comments,
+                'all_comments': all_comments
+            }
+        }
diff --git a/tests/test_atal.py b/tests/test_atal.py
index f038d864..beb6ef3e 100644
--- a/tests/test_atal.py
+++ b/tests/test_atal.py
@@ -1,9 +1,11 @@
 # coding: utf-8
 
 import base64
+from datetime import datetime
 import os
 
 from django.contrib.contenttypes.models import ContentType
+from django.utils.http import urlencode
 import mock
 import pytest
 
@@ -323,3 +325,52 @@ def test_infos(app, connector, monkeypatch):
     }
     assert data['works_comments'][1] == last_comment
     assert data['works_comment'] == last_comment
+
+
+def test_new_comments(app, connector, monkeypatch):
+    import passerelle.utils
+
+    wsdl_response = mock.Mock(
+        content=get_file('DemandeService.wsdl'), status_code=200,
+        headers={'Content-Type': 'text/xml'}
+    )
+    monkeypatch.setattr(passerelle.utils.Request, 'get', mock.Mock(return_value=wsdl_response))
+
+    api_response = mock.Mock(
+        content=get_file('details_demande_response_with_comments.xml'), status_code=200,
+        headers={'Content-Type': 'text/xml'}
+    )
+    monkeypatch.setattr(passerelle.utils.Request, 'post', mock.Mock(return_value=api_response))
+
+    all_comments = [
+        {
+            'text': 'OK',
+            'date': 'Thursday 24 October 2019, 16:48',
+            'date_raw': '2019-10-24T16:48:34+02:00'
+        }, {
+            'text': 'bonjour atal',
+            'date': 'Thursday 24 October 2019, 16:51',
+            'date_raw': '2019-10-24T16:51:37+02:00'
+        }
+    ]
+
+    last_datetime = datetime(year=2019, month=10, day=23)
+    params = urlencode({'last_datetime': last_datetime})
+    response = app.get('/atal/slug-atal/new-comments/DIT18050001/?%s' % params)
+    assert response.json['err'] == 0
+    assert response.json['data']['new_comments'] == all_comments
+    assert response.json['data']['all_comments'] == all_comments
+
+    last_datetime = datetime(year=2019, month=10, day=24, hour=16, minute=49)
+    params = urlencode({'last_datetime': last_datetime})
+    response = app.get('/atal/slug-atal/new-comments/DIT18050001/?%s' % params)
+    assert response.json['err'] == 0
+    assert response.json['data']['new_comments'] == all_comments[1:]
+    assert response.json['data']['all_comments'] == all_comments
+
+    last_datetime = datetime(year=2019, month=10, day=24, hour=16, minute=52)
+    params = urlencode({'last_datetime': last_datetime})
+    response = app.get('/atal/slug-atal/new-comments/DIT18050001/?%s' % params)
+    assert response.json['err'] == 0
+    assert response.json['data']['new_comments'] == []
+    assert response.json['data']['all_comments'] == all_comments
-- 
2.20.1

