From c375a664227324af86812746fc9fd7143846a344 Mon Sep 17 00:00:00 2001
From: Nicolas ROCHE <nroche@entrouvert.com>
Date: Tue, 11 May 2021 15:08:27 +0200
Subject: [PATCH 2/4] caluire-axel: add invoices_history endpoint (#53884)

---
 passerelle/contrib/caluire_axel/models.py     |  59 +++++++++
 passerelle/contrib/caluire_axel/schemas.py    |   1 +
 .../caluire_axel/xsd/Q_GetListFactures.xsd    |  28 +++++
 .../caluire_axel/xsd/R_GetListFactures.xsd    |  55 +++++++++
 tests/test_caluire_axel.py                    | 112 ++++++++++++++++++
 5 files changed, 255 insertions(+)
 create mode 100644 passerelle/contrib/caluire_axel/xsd/Q_GetListFactures.xsd
 create mode 100644 passerelle/contrib/caluire_axel/xsd/R_GetListFactures.xsd

diff --git a/passerelle/contrib/caluire_axel/models.py b/passerelle/contrib/caluire_axel/models.py
index a84e8485..91df64e0 100644
--- a/passerelle/contrib/caluire_axel/models.py
+++ b/passerelle/contrib/caluire_axel/models.py
@@ -563,16 +563,54 @@ class CaluireAxel(BaseResource):
 
         data = result.json_response['DATA']['PORTAIL']['GETFACTURESAPAYER']
         result = []
 
         for facture in data.get('FACTURE', []):
             result.append(utils.normalize_invoice(facture, family_id))
         return result
 
+    def get_historical_invoices(self, regie_id, family_id, nb_mounts_limit):
+        try:
+            nb_mois = int(nb_mounts_limit)
+        except ValueError:
+            raise APIError('nb_mounts_limit must be an integer', err_code='bad-request', http_status=400)
+        try:
+            result = schemas.get_list_factures(
+                self,
+                {
+                    'PORTAIL': {
+                        'GETLISTFACTURES': {
+                            'IDENTFAMILLE': family_id,
+                            'IDENTREGIEFACT': regie_id,
+                            'NBMOIS': nb_mois,
+                        }
+                    },
+                },
+            )
+        except axel.AxelError as e:
+            raise APIError(
+                'Axel error: %s' % e,
+                err_code='error',
+                data={'xml_request': e.xml_request, 'xml_response': e.xml_response},
+            )
+
+        code = result.json_response['DATA']['PORTAIL']['GETLISTFACTURES']['CODE']
+        if code < 0:
+            raise APIError(
+                'Wrong get-historical-invoices status',
+                err_code='get-historical-invoices-code-error-%s' % code,
+            )
+
+        data = result.json_response['DATA']['PORTAIL']['GETLISTFACTURES']
+        result = []
+        for facture in data.get('FACTURE', []):
+            result.append(utils.normalize_invoice(facture, family_id, historical=True))
+        return result
+
     @endpoint(
         display_category=_('Invoices'),
         display_order=1,
         name='regie',
         perm='can_access',
         pattern=r'^(?P<regie_id>[\w-]+)/invoices/?$',
         example_pattern='{regie_id}/invoices',
         description=_("Get invoices to pay"),
@@ -581,16 +619,37 @@ class CaluireAxel(BaseResource):
             'regie_id': {'description': _('Regie identifier'), 'example_value': 'ENF'},
         },
     )
     def invoices(self, request, regie_id, NameID):
         link = self.get_link(NameID)
         invoices_data = self.get_invoices(regie_id=regie_id, family_id=link.family_id)
         return {'data': invoices_data}
 
+    @endpoint(
+        display_category=_('Invoices'),
+        display_order=2,
+        name='regie',
+        perm='can_access',
+        pattern=r'^(?P<regie_id>[\w-]+)/invoices/history/?$',
+        example_pattern='{regie_id}/invoices/history',
+        description=_("Get invoices already paid"),
+        parameters={
+            'NameID': {'description': _('Publik ID')},
+            'regie_id': {'description': _('Regie identifier'), 'example_value': 'ENF'},
+            'nb_mounts_limit': {'description': _('Number of months of history'), 'example_value': '3'},
+        },
+    )
+    def invoices_history(self, request, regie_id, NameID, nb_mounts_limit='3'):
+        link = self.get_link(NameID)
+        invoices_data = self.get_historical_invoices(
+            regie_id, family_id=link.family_id, nb_mounts_limit=nb_mounts_limit
+        )
+        return {'data': invoices_data}
+
 
 class Link(models.Model):
     resource = models.ForeignKey(CaluireAxel, on_delete=models.CASCADE)
     name_id = models.CharField(blank=False, max_length=256)
     family_id = models.CharField(blank=False, max_length=128)
     person_id = models.CharField(blank=False, max_length=128)
 
     class Meta:
diff --git a/passerelle/contrib/caluire_axel/schemas.py b/passerelle/contrib/caluire_axel/schemas.py
index a6b99342..df5420f3 100644
--- a/passerelle/contrib/caluire_axel/schemas.py
+++ b/passerelle/contrib/caluire_axel/schemas.py
@@ -75,16 +75,17 @@ class Operation(axel.Operation):
 find_individus = Operation('FindIndividus')
 get_famille_individus = Operation('GetFamilleIndividus')
 get_individu = Operation('GetIndividu')
 get_list_ecole = Operation('GetListEcole')
 get_list_activites = Operation('GetListActivites')
 create_inscription_activite = Operation('CreateInscriptionActivite', data_method='setData')
 get_agenda = Operation('GetAgenda')
 get_factures_a_payer = Operation('GetFacturesaPayer')
+get_list_factures = Operation('GetListFactures')
 
 
 LINK_SCHEMA = copy.deepcopy(
     find_individus.request_schema['properties']['PORTAIL']['properties']['FINDINDIVIDU']
 )
 for key in ['NAISSANCE', 'CODEPOSTAL', 'VILLE', 'TEL', 'MAIL']:
     LINK_SCHEMA['properties'].pop(key)
     LINK_SCHEMA['required'].remove(key)
diff --git a/passerelle/contrib/caluire_axel/xsd/Q_GetListFactures.xsd b/passerelle/contrib/caluire_axel/xsd/Q_GetListFactures.xsd
new file mode 100644
index 00000000..39fa5562
--- /dev/null
+++ b/passerelle/contrib/caluire_axel/xsd/Q_GetListFactures.xsd
@@ -0,0 +1,28 @@
+<?xml version="1.0" encoding="utf-8" ?>
+<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:all="urn:AllAxelTypes">
+	
+	<xsd:import schemaLocation="./AllAxelTypes.xsd" namespace="urn:AllAxelTypes"  />
+		
+	<xsd:complexType name="PORTAILType">
+		<xsd:sequence>
+			<xsd:element ref="GETLISTFACTURES" minOccurs="0" maxOccurs="1"/>
+		</xsd:sequence>  
+	</xsd:complexType>
+	
+	<xsd:complexType name="GETLISTFACTURESType">
+		<xsd:sequence>
+			<xsd:element ref="IDENTFAMILLE"/>
+			<xsd:element ref="IDENTREGIEFACT"/>
+			<xsd:element ref="NBMOIS"/>
+		</xsd:sequence>  
+	</xsd:complexType>
+	
+	<xsd:element name="IDENTFAMILLE" type="all:IDENTREQUIREDType"/>
+	<xsd:element name="IDENTREGIEFACT" type="all:IDREQUIREDType"/>
+	<xsd:element name="NBMOIS" type="xsd:unsignedInt"/>
+	
+	<xsd:element name="GETLISTFACTURES" type="GETLISTFACTURESType"/>
+	
+	<xsd:element name="PORTAIL" type="PORTAILType"/>	
+		
+</xsd:schema>
\ No newline at end of file
diff --git a/passerelle/contrib/caluire_axel/xsd/R_GetListFactures.xsd b/passerelle/contrib/caluire_axel/xsd/R_GetListFactures.xsd
new file mode 100644
index 00000000..9f5ed1f0
--- /dev/null
+++ b/passerelle/contrib/caluire_axel/xsd/R_GetListFactures.xsd
@@ -0,0 +1,55 @@
+<?xml version="1.0" encoding="utf-8" ?>
+<xsd:schema	xmlns:all="urn:AllAxelTypes" xmlns:ind="urn:Individu"  xmlns:xsd="http://www.w3.org/2001/XMLSchema" >
+	
+	<xsd:import schemaLocation="./AllAxelTypes.xsd" namespace="urn:AllAxelTypes" />
+	
+	<xsd:redefine schemaLocation="./R_ShemaResultat.xsd">
+	    <xsd:simpleType name="TYPEType">
+			<xsd:restriction base="TYPEType">
+				<xsd:enumeration value="GetListFactures" />
+			</xsd:restriction>
+	    </xsd:simpleType>
+		
+		<xsd:complexType name="PORTAILType">
+			<xsd:complexContent>
+				<xsd:extension base="PORTAILType">
+					<xsd:sequence>
+							<xsd:element ref="GETLISTFACTURES" minOccurs="0" maxOccurs="1"/>
+					</xsd:sequence>
+				</xsd:extension>
+			 </xsd:complexContent>
+		</xsd:complexType>
+	</xsd:redefine>	
+	
+	<xsd:complexType name="FACTUREType">
+		<xsd:sequence>
+			<xsd:element ref="IDFACTURE" />
+			<xsd:element ref="MONTANT"/>
+			<xsd:element ref="ENCAISSE"/>
+			<xsd:element ref="FACTURATION"/>
+			<xsd:element ref="EMISSION"/><!-- CUSTOM -->
+			<xsd:element ref="ECHEANCE"/><!-- CUSTOM -->
+			<xsd:element ref="EXISTEPDF"/>
+		</xsd:sequence> 
+	</xsd:complexType>
+	
+	<xsd:complexType name="GETLISTFACTURESType">
+		<xsd:sequence>
+			<xsd:element ref="CODE" />
+			<xsd:element ref="FACTURE" minOccurs="0" maxOccurs="unbounded" />
+		</xsd:sequence>
+	</xsd:complexType>
+	
+	<xsd:element name="CODE" type="xsd:integer"/>	
+	<xsd:element name="IDFACTURE" type="xsd:positiveInteger"/>
+	<xsd:element name="MONTANT" type="all:MONTANTType"/>
+	<xsd:element name="ENCAISSE" type="all:MONTANTType"/>
+	<xsd:element name="FACTURATION" type="all:NOMType"/>
+	<xsd:element name="EMISSION" type="all:DATEType"/><!-- CUSTOM -->
+	<xsd:element name="ECHEANCE" type="all:DATEType"/><!-- CUSTOM -->
+	<xsd:element name="EXISTEPDF" type="all:ONEmptyType"/>
+	<xsd:element name="FACTURE" type="FACTUREType"/>
+	
+	<xsd:element name="GETLISTFACTURES" type="GETLISTFACTURESType"/>
+	
+</xsd:schema>
diff --git a/tests/test_caluire_axel.py b/tests/test_caluire_axel.py
index 08cd3492..332a3941 100644
--- a/tests/test_caluire_axel.py
+++ b/tests/test_caluire_axel.py
@@ -1270,8 +1270,120 @@ def test_invoices_endpoint(app, resource):
                     'ENCAISSE': '0.00',
                     'ECHEANCE': '2020-01-04',
                     'EMISSION': '2019-12-12',
                     'EXISTEPDF': False,
                 }
             },
         },
     ]
+
+
+def test_invoices_history_endpoint_axel_error(app, resource):
+    Link.objects.create(resource=resource, name_id='yyy', family_id='XXX', person_id='42')
+    with mock.patch('passerelle.contrib.caluire_axel.schemas.get_list_factures') as operation:
+        operation.side_effect = AxelError('FooBar')
+        resp = app.get('/caluire-axel/test/regie/MAREGIE/invoices/history?NameID=yyy')
+    assert resp.json['err_desc'] == "Axel error: FooBar"
+    assert resp.json['err'] == 'error'
+
+    content = '''<PORTAIL>
+    <GETLISTFACTURES>
+        <CODE>-3</CODE>
+    </GETLISTFACTURES>
+</PORTAIL>'''
+    with mock_data(content, 'GetListFactures'):
+        resp = app.get('/caluire-axel/test/regie/MAREGIE/invoices/history?NameID=yyy')
+    assert resp.json['err_desc'] == "Wrong get-historical-invoices status"
+    assert resp.json['err'] == 'get-historical-invoices-code-error--3'
+
+
+def test_invoices_history_endpoint_bad_request(app, resource):
+    Link.objects.create(resource=resource, name_id='yyy', family_id='XXX', person_id='42')
+    with mock_data(None, 'GetListFactures'):
+        resp = app.get(
+            '/caluire-axel/test/regie/MAREGIE/invoices/history?NameID=yyy&nb_mounts_limit=not_a_number',
+            status=400,
+        )
+    assert resp.json['err_desc'] == "nb_mounts_limit must be an integer"
+    assert resp.json['err'] == 'bad-request'
+
+
+def test_invoices_history_endpoint_no_result(app, resource):
+    resp = app.get('/caluire-axel/test/regie/MAREGIE/invoices/history?NameID=yyy')
+    assert resp.json['err_desc'] == "Person not found"
+    assert resp.json['err'] == 'not-found'
+
+
+def test_invoices_history_endpoint_no_invoice(app, resource):
+    Link.objects.create(resource=resource, name_id='yyy', family_id='XXX', person_id='42')
+    content = '''<PORTAIL>
+    <GETLISTFACTURES>
+        <CODE>0</CODE>
+    </GETLISTFACTURES>
+</PORTAIL>'''
+    with mock_data(content, 'GetListFactures'):
+        resp = app.get('/caluire-axel/test/regie/MAREGIE/invoices/history?NameID=yyy')
+    assert resp.json['err'] == 0
+    assert resp.json['data'] == []
+
+
+def test_invoices_history_endpoint(app, resource):
+    Link.objects.create(resource=resource, name_id='yyy', family_id='XXX', person_id='42')
+    filepath = os.path.join(os.path.dirname(__file__), 'data/caluire_axel/invoices.xml')
+    with open(filepath) as xml:
+        content = (
+            '''<PORTAIL>
+    <GETLISTFACTURES>
+        %s
+    </GETLISTFACTURES>
+</PORTAIL>'''
+            % xml.read()
+        )
+    with mock_data(content, 'GetListFactures'):
+        resp = app.get('/caluire-axel/test/regie/MAREGIE/invoices/history?NameID=yyy')
+    assert resp.json['err'] == 0
+    assert resp.json['data'] == [
+        {
+            'id': 'historical-XXX-42',
+            'display_id': '42',
+            'label': 'PRESTATIONS PERISCOLAIRES SEPTEMBRE-OCTOBRE 2019',
+            'amount': 0,
+            'total_amount': '44.94',
+            'online_payment': False,
+            'pay_limit_date': '',
+            'has_pdf': True,
+            'paid': False,
+            'vendor': {
+                'caluire-axel': {
+                    'IDFACTURE': 42,
+                    'MONTANT': '44.94',
+                    'ENCAISSE': '40.00',
+                    'FACTURATION': 'PRESTATIONS PERISCOLAIRES SEPTEMBRE-OCTOBRE 2019',
+                    'ECHEANCE': '2019-12-04',
+                    'EMISSION': '2019-11-12',
+                    'EXISTEPDF': True,
+                }
+            },
+        },
+        {
+            'id': 'historical-XXX-43',
+            'display_id': '43',
+            'label': 'PRESTATIONS PERISCOLAIRES NOVEMBRE 2019',
+            'amount': 0,
+            'total_amount': '44.94',
+            'online_payment': False,
+            'pay_limit_date': '',
+            'has_pdf': False,
+            'paid': False,
+            'vendor': {
+                'caluire-axel': {
+                    'IDFACTURE': 43,
+                    'FACTURATION': 'PRESTATIONS PERISCOLAIRES NOVEMBRE 2019',
+                    'MONTANT': '44.94',
+                    'ENCAISSE': '0.00',
+                    'ECHEANCE': '2020-01-04',
+                    'EMISSION': '2019-12-12',
+                    'EXISTEPDF': False,
+                }
+            },
+        },
+    ]
-- 
2.30.2

