From 3141d414dac9268a2726ea4c4b4427e1d8f00ef6 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Fr=C3=A9d=C3=A9ric=20P=C3=A9ters?= <fpeters@entrouvert.com>
Date: Wed, 11 Sep 2019 11:11:05 +0200
Subject: [PATCH] cartads_cs: add endpoint to get list of additionnal pieces
 (#36024)

---
 passerelle/apps/cartads_cs/models.py | 34 ++++++++++++++++++++
 tests/test_cartads_cs.py             | 47 ++++++++++++++++++++++++++++
 2 files changed, 81 insertions(+)

diff --git a/passerelle/apps/cartads_cs/models.py b/passerelle/apps/cartads_cs/models.py
index 1860bc6e..b2fc6da0 100644
--- a/passerelle/apps/cartads_cs/models.py
+++ b/passerelle/apps/cartads_cs/models.py
@@ -447,6 +447,40 @@ class AbstractCartaDSCS(BaseResource):
                 break
         return {'result': result}
 
+    @endpoint(perm='can_access',
+              description=_('Get list of additional file items'),
+              parameters={
+                  'tracking_code': TRACKING_CODE_PARAM,
+              })
+    def additional_pieces(self, request, tracking_code):
+        client = self.soap_client(wsdl_url=self.get_wsdl_url('ServicePiece'))
+        dossier = CartaDSDossier.objects.get(tracking_code=tracking_code)
+        resp = client.service.GetPiecesDossierACompleter(self.get_token(), dossier.cartads_id_dossier)
+
+        signer = Signer(salt='cart@ds_cs')
+        upload_token = signer.sign(tracking_code)
+
+        pieces = [
+            {'id': 'comp-%s-%s' % (x['IdDosPiece'], x['IdPiece']),
+             'text': x['LibellePiece'],
+             'description': x['Descriptif'],
+             'codePiece': x['CodePiece'],
+             'files': [],
+             'max_files': 6,
+             } for x in resp]
+
+        for piece in pieces:
+            if request:
+                upload_url = request.build_absolute_uri('%supload/%s/%s/' % (
+                    self.get_absolute_url(),
+                    piece['id'],
+                    upload_token))
+            else:
+                upload_url = None
+            piece['files'] = []
+            piece['files'].append({'url': upload_url})
+        return {'data': pieces}
+
     @endpoint(methods=['post'],
               pattern='^(?P<id_piece>[\w-]+)/(?P<token>[\w:_-]+)/$',
               description=_('Upload a single document file'),
diff --git a/tests/test_cartads_cs.py b/tests/test_cartads_cs.py
index 90f5732d..37991b48 100644
--- a/tests/test_cartads_cs.py
+++ b/tests/test_cartads_cs.py
@@ -1,5 +1,6 @@
 # -*- coding: utf-8 -*-
 
+from collections import OrderedDict
 import datetime
 import os
 
@@ -83,6 +84,30 @@ class FakeService():
             'LibelleEtape': 'En cours de saisie'
             }]
 
+    def GetPiecesDossierACompleter(self, token, dossier_id):
+        return [
+            OrderedDict([
+                (u'CodePiece', 'PC07'),
+                (u'DateDemande', datetime.datetime(2019, 4, 15, 0, 0)),
+                (u'DatePresentation', None),
+                (u'DateReception', None),
+                (u'Descriptif', u"Un document graphique..."),
+                (u'IdDosPiece', 133837L),
+                (u'IdPiece', 58L),
+                (u'LibellePiece', u"Document graphique permettant..."),
+                (u'NbDocuments', 0L)]),
+            OrderedDict([
+                (u'CodePiece', 'PC16-1'),
+                (u'DateDemande', datetime.datetime(2019, 4, 15, 0, 0)),
+                (u'DatePresentation', None),
+                (u'DateReception', None),
+                (u'Descriptif', u'Formulaire attestant...'),
+                (u'IdDosPiece', 133840L),
+                (u'IdPiece', 99L),
+                (u'LibellePiece', u'Formulaire attestant...'),
+                (u'NbDocuments', 0L)]),
+        ]
+
 
 def pdf_mock(url, request):
     return {'content': '%PDF...', 'status_code': 200}
@@ -315,3 +340,25 @@ def test_status_error(connector, app, cached_data):
 
     resp = app.get('/cartads-cs/test/status?dossier_id=%s' % dossier.id)
     assert resp.json['status_label'] == u"File refused (Le modèle sélectionné ne correspond à aucun Cerfa géré par l'application.)"
+
+
+def test_additional_pieces_management(connector, app, cached_data):
+    CartaDSDossier.objects.all().delete()
+    test_send(connector, app, cached_data)
+    dossier = CartaDSDossier.objects.all()[0]
+    with mock.patch('passerelle.apps.cartads_cs.models.CartaDSCS.soap_client') as client:
+        client.return_value = mock.Mock(service=FakeService())
+        resp = app.get('/cartads-cs/test/additional_pieces?tracking_code=%s' % dossier.tracking_code)
+    data = resp.json['data']
+    assert len(data) == 2
+    assert data[0]['text'] == 'Document graphique permettant...'
+    assert data[0]['max_files'] == 6
+    assert data[1]['text'] == u'Formulaire attestant...'
+    assert data[1]['max_files'] == 6
+    for piece in data:
+        assert len(piece['files']) == 1
+        assert piece['files'][0].keys() == ['url']
+
+    resp = app.post(data[0]['files'][0]['url'],
+                    upload_files=[('files[]', 'test.pdf', '%PDF...')])
+    assert resp.json[0]['token']
-- 
2.23.0

