Projet

Général

Profil

0001-caluire-axel-set_activity_agenda_typical_week-endpoi.patch

Lauréline Guérin, 21 juin 2021 11:54

Télécharger (29,3 ko)

Voir les différences:

Subject: [PATCH] caluire-axel: set_activity_agenda_typical_week endpoint
 (#54383)

 passerelle/contrib/caluire_axel/models.py  | 181 ++++++---
 passerelle/contrib/caluire_axel/schemas.py |  32 ++
 tests/test_caluire_axel.py                 | 405 +++++++++++++++++++++
 3 files changed, 560 insertions(+), 58 deletions(-)
passerelle/contrib/caluire_axel/models.py
27 27
from django.utils.translation import ugettext_lazy as _
28 28

  
29 29
from passerelle.base.models import BaseResource
30
from passerelle.compat import json_loads
31 30
from passerelle.contrib.utils import axel
32 31
from passerelle.utils.api import endpoint
33 32
from passerelle.utils.jsonresponse import APIError
34 33

  
35 34
from . import schemas, utils
36 35

  
36
WEEKDAYS = {
37
    0: 'monday',
38
    1: 'tuesday',
39
    2: 'wednesday',
40
    3: 'thursday',
41
    4: 'friday',
42
    5: 'saturday',
43
    6: 'sunday',
44
}
45

  
37 46

  
38 47
class CaluireAxel(BaseResource):
39 48

  
......
532 541
            },
533 542
        }
534 543

  
535
    def get_bookings(self, child_id, activity_id, activity_label, start_date, end_date):
544
    def get_bookings(self, child_id, activity_id, start_date, end_date, activity_label=None):
536 545
        data = {
537 546
            'IDENTINDIVIDU': child_id,
538 547
            'IDENTACTIVITE': activity_id,
......
620 629
                booking['disabled'] = True if day_date < datetime.date.today() or color == 'grey' else False
621 630
            booking['details']['activity_id'] = activity_id
622 631
            booking['details']['activity_type'] = activity_type
623
            booking['details']['activity_label'] = activity_label
632
            if activity_label:
633
                booking['details']['activity_label'] = activity_label
624 634
            booking['details']['child_id'] = child_id
625 635
            bookings.append(booking)
626 636

  
......
651 661
        if activity_data is None:
652 662
            raise APIError('Activity not found', err_code='not-found')
653 663
        bookings = self.get_bookings(
654
            idpersonne, activity_id, activity_data['LIBELLEACTIVITE'], start_date, end_date
664
            idpersonne, activity_id, start_date, end_date, activity_label=activity_data['LIBELLEACTIVITE']
655 665
        )
656 666
        return {'data': bookings}
657 667

  
......
683 693
            if activity_id.startswith('CJ') and not activity_id.startswith('CJ MER'):
684 694
                # vacances: ignore id
685 695
                continue
686
            bookings += self.get_bookings(idpersonne, activity_id, activity_label, start_date, end_date)
696
            bookings += self.get_bookings(
697
                idpersonne, activity_id, start_date, end_date, activity_label=activity_label
698
            )
687 699

  
688 700
        # sort bookings
689 701
        activity_types = ['matin', 'midi', 'soir', 'mercredi']
......
701 713

  
702 714
        return {'data': bookings}
703 715

  
716
    def set_bookings(self, child_id, activity_id, start_date, end_date, booking_list):
717
        agenda = self.get_bookings(child_id, activity_id, start_date, end_date)
718
        legacy_days = [b['id'] for b in agenda if b['prefill'] is True]
719
        available_days = [b['id'] for b in agenda if b['disabled'] is False]
720
        booking_date = start_date
721
        bookings = []
722
        while booking_date <= end_date:
723
            day = booking_date.strftime(axel.json_date_format)
724
            day_id = '%s:%s:%s' % (child_id, activity_id, day)
725
            booked = None
726
            if day_id not in available_days:
727
                # disabled or not available: not bookable
728
                booked = None
729
            elif day_id not in legacy_days and day_id in booking_list:
730
                booked = 'X'
731
            elif day_id in legacy_days and day_id not in booking_list:
732
                booked = 'D'
733
            if booked is not None:
734
                # no changes, don't send the day
735
                bookings.append(
736
                    {
737
                        'JOURDATE': day,
738
                        'MATIN': booked,
739
                        'MIDI': None,
740
                        'APRESMIDI': None,
741
                    }
742
                )
743
            booking_date += datetime.timedelta(days=1)
744
        if not bookings:
745
            # don't call axel if no changes
746
            return 0
747
        try:
748
            data = {
749
                'PORTAIL': {
750
                    'SETAGENDA': {
751
                        'IDENTINDIVIDU': child_id,
752
                        'ACTIVITE': {
753
                            'IDENTACTIVITE': activity_id,
754
                            'JOUR': bookings,
755
                        },
756
                    }
757
                }
758
            }
759
            result = schemas.set_agenda(self, data)
760
        except axel.AxelError as e:
761
            raise APIError(
762
                'Axel error: %s' % e,
763
                err_code='error',
764
                data={'xml_request': e.xml_request, 'xml_response': e.xml_response},
765
            )
766

  
767
        code = result.json_response['DATA']['PORTAIL']['SETAGENDA']['CODE']
768
        if code != 0:
769
            raise APIError('Wrong agenda status', err_code='agenda-code-error-%s' % code)
770

  
771
        return len(bookings)
772

  
704 773
    @endpoint(
705 774
        display_category=_('Schooling'),
706 775
        display_order=7,
......
746 815
        updated = 0
747 816
        for activity in activities_data.get('ACTIVITE', []):
748 817
            activity_id = activity['IDENTACTIVITE']
749
            activity_label = activity['LIBELLEACTIVITE']
750 818
            if activity_id.startswith('CJ'):
751 819
                # mercredi or vacances: not bookable
752 820
                continue
753
            agenda = self.get_bookings(child_id, activity_id, activity_label, start_date, end_date)
754
            legacy_days = [b['id'] for b in agenda if b['prefill'] is True]
755
            available_days = [b['id'] for b in agenda if b['disabled'] is False]
756
            booking_date = start_date
757
            bookings = []
758
            while booking_date <= end_date:
759
                day = booking_date.strftime(axel.json_date_format)
760
                day_id = '%s:%s:%s' % (child_id, activity_id, day)
761
                booked = None
762
                if day_id not in available_days:
763
                    # disabled or not available: not bookable
764
                    booked = None
765
                elif day_id not in legacy_days and day_id in post_data['booking_list']:
766
                    booked = 'X'
767
                elif day_id in legacy_days and day_id not in post_data['booking_list']:
768
                    booked = 'D'
769
                if booked is not None:
770
                    # no changes, don't send the day
771
                    bookings.append(
772
                        {
773
                            'JOURDATE': day,
774
                            'MATIN': booked,
775
                            'MIDI': None,
776
                            'APRESMIDI': None,
777
                        }
778
                    )
779
                booking_date += datetime.timedelta(days=1)
780
            if not bookings:
781
                # don't call axel if no changes
782
                continue
783
            try:
784
                data = {
785
                    'PORTAIL': {
786
                        'SETAGENDA': {
787
                            'IDENTINDIVIDU': child_id,
788
                            'ACTIVITE': {
789
                                'IDENTACTIVITE': activity_id,
790
                                'JOUR': bookings,
791
                            },
792
                        }
793
                    }
821
            updated += self.set_bookings(
822
                child_id, activity_id, start_date, end_date, post_data['booking_list']
823
            )
824

  
825
        return {
826
            'updated': True,
827
            'count': updated,
828
        }
829

  
830
    @endpoint(
831
        display_category=_('Schooling'),
832
        display_order=7,
833
        description=_("Set activity agenda for a child with a typical week"),
834
        perm='can_access',
835
        parameters={
836
            'NameID': {'description': _('Publik ID')},
837
        },
838
        post={
839
            'request_body': {
840
                'schema': {
841
                    'application/json': schemas.TYPICAL_WEEK_BOOKING_SCHEMA,
794 842
                }
795
                result = schemas.set_agenda(self, data)
796
            except axel.AxelError as e:
797
                raise APIError(
798
                    'Axel error: %s' % e,
799
                    err_code='error',
800
                    data={'xml_request': e.xml_request, 'xml_response': e.xml_response},
801
                )
843
            }
844
        },
845
    )
846
    def set_activity_agenda_typical_week(self, request, NameID, post_data):
847
        link = self.get_link(NameID)
848
        child_id = post_data['child_id']
849
        child_data = self.get_child_data(link.family_id, child_id)
850
        if child_data is None:
851
            raise APIError('Child not found', err_code='not-found')
852
        start_date, end_date, reference_year = self.get_start_and_end_dates(
853
            post_data['start_date'], post_data['end_date']
854
        )
855
        activity_id = post_data['activity_id']
856
        activity_data = self.get_child_activity(child_id, activity_id, reference_year)
857
        if activity_data is None:
858
            raise APIError('Activity not found', err_code='not-found')
802 859

  
803
            code = result.json_response['DATA']['PORTAIL']['SETAGENDA']['CODE']
804
            if code != 0:
805
                raise APIError('Wrong agenda status', err_code='agenda-code-error-%s' % code)
860
        if activity_id.startswith('CJ'):
861
            raise APIError('Not available for this activity', err_code='bad-request', http_status=400)
862

  
863
        booking_date = start_date
864
        bookings = []
865
        while booking_date <= end_date:
866
            if WEEKDAYS[booking_date.weekday()] in post_data['booking_list']:
867
                bookings.append(
868
                    '%s:%s:%s' % (child_id, activity_id, booking_date.strftime(axel.json_date_format))
869
                )
870
            booking_date += datetime.timedelta(days=1)
806 871

  
807
            updated += len(bookings)
872
        updated = self.set_bookings(child_id, activity_id, start_date, end_date, bookings)
808 873

  
809 874
        return {
810 875
            'updated': True,
passerelle/contrib/caluire_axel/schemas.py
147 147
    ],
148 148
}
149 149

  
150
TYPICAL_WEEK_BOOKING_SCHEMA = {
151
    'type': 'object',
152
    'properties': {
153
        'child_id': {
154
            'type': 'string',
155
            'minLength': 1,
156
            'maxLength': 8,
157
        },
158
        'activity_id': {
159
            'type': 'string',
160
            'minLength': 1,
161
            'maxLength': 10,
162
        },
163
        'booking_list': {
164
            'type': 'array',
165
            'items': {
166
                'type': 'string',
167
                'pattern': '(monday|tuesday|thursday|friday)',
168
            },
169
        },
170
        'start_date': copy.deepcopy(axel.date_type),
171
        'end_date': copy.deepcopy(axel.date_type),
172
    },
173
    'required': [
174
        'child_id',
175
        'activity_id',
176
        'booking_list',
177
        'start_date',
178
        'end_date',
179
    ],
180
}
181

  
150 182

  
151 183
PAYMENT_SCHEMA = {
152 184
    'type': 'object',
tests/test_caluire_axel.py
147 147
    }
148 148

  
149 149

  
150
@pytest.fixture
151
def week_booking_params():
152
    return {
153
        'child_id': '50632',
154
        'activity_id': 'ELEM',
155
        'booking_list': [],
156
        'start_date': '2020-09-01',
157
        'end_date': '2021-08-31',
158
    }
159

  
160

  
150 161
@pytest.fixture
151 162
def upload_attachments_params():
152 163
    return {
......
2020 2031
    assert resp.json['err'] == 'agenda-code-error-%s' % code
2021 2032

  
2022 2033

  
2034
@freezegun.freeze_time('2020-08-01')
2035
def test_set_activity_agenda_typical_week_endpoint_axel_error(
2036
    app, resource, family_data, activities, week_booking_params
2037
):
2038
    Link.objects.create(resource=resource, name_id='yyy', family_id='XXX', person_id='42')
2039
    week_booking_params['booking_list'] = ['monday']
2040
    with mock.patch('passerelle.contrib.caluire_axel.schemas.get_famille_individus') as operation:
2041
        operation.side_effect = AxelError('FooBar')
2042
        resp = app.post_json(
2043
            '/caluire-axel/test/set_activity_agenda_typical_week?NameID=yyy', params=week_booking_params
2044
        )
2045
    assert resp.json['err_desc'] == "Axel error: FooBar"
2046
    assert resp.json['err'] == 'error'
2047

  
2048
    filepath = os.path.join(os.path.dirname(__file__), 'data/caluire_axel/family_info.xml')
2049
    with open(filepath) as xml:
2050
        content = xml.read()
2051
    with mock_data(content, 'GetFamilleIndividus'):
2052
        with mock.patch('passerelle.contrib.caluire_axel.schemas.get_list_activites') as operation:
2053
            operation.side_effect = AxelError('FooBar')
2054
            resp = app.post_json(
2055
                '/caluire-axel/test/set_activity_agenda_typical_week?NameID=yyy', params=week_booking_params
2056
            )
2057
    assert resp.json['err_desc'] == "Axel error: FooBar"
2058
    assert resp.json['err'] == 'error'
2059

  
2060
    filepath = os.path.join(os.path.dirname(__file__), 'data/caluire_axel/activities_info.xml')
2061
    with open(filepath) as xml:
2062
        content = xml.read()
2063
    with mock_data(content, 'GetListActivites'):
2064
        with mock.patch(
2065
            'passerelle.contrib.caluire_axel.models.CaluireAxel.get_family_data',
2066
            return_value=family_data,
2067
        ):
2068
            with mock.patch('passerelle.contrib.caluire_axel.schemas.get_agenda') as operation:
2069
                operation.side_effect = AxelError('FooBar')
2070
                resp = app.post_json(
2071
                    '/caluire-axel/test/set_activity_agenda_typical_week?NameID=yyy',
2072
                    params=week_booking_params,
2073
                )
2074
    assert resp.json['err_desc'] == "Axel error: FooBar"
2075
    assert resp.json['err'] == 'error'
2076

  
2077
    content = '''<PORTAIL>
2078
    <GETAGENDA>
2079
        <CODE>1</CODE>
2080
        <JOUR>
2081
          <JOURDATE>07/09/2020</JOURDATE>
2082
          <MATIN>.</MATIN>
2083
          <MIDI></MIDI>
2084
          <APRESMIDI></APRESMIDI>
2085
          <FERME>N</FERME>
2086
        </JOUR>
2087
    </GETAGENDA>
2088
</PORTAIL>'''
2089
    with mock_data(content, 'GetAgenda'):
2090
        with mock.patch(
2091
            'passerelle.contrib.caluire_axel.models.CaluireAxel.get_family_data',
2092
            return_value=family_data,
2093
        ):
2094
            with mock.patch(
2095
                'passerelle.contrib.caluire_axel.models.CaluireAxel.get_child_activities',
2096
                return_value=activities,
2097
            ):
2098
                with mock.patch('passerelle.contrib.caluire_axel.schemas.set_agenda') as operation:
2099
                    operation.side_effect = AxelError('FooBar')
2100
                    resp = app.post_json(
2101
                        '/caluire-axel/test/set_activity_agenda_typical_week?NameID=yyy',
2102
                        params=week_booking_params,
2103
                    )
2104
    assert resp.json['err_desc'] == "Axel error: FooBar"
2105
    assert resp.json['err'] == 'error'
2106

  
2107

  
2108
def test_set_activity_agenda_typical_week_endpoint_no_result(app, resource, week_booking_params):
2109
    week_booking_params['child_id'] = 'zzz'
2110
    resp = app.post_json(
2111
        '/caluire-axel/test/set_activity_agenda_typical_week?NameID=yyy', params=week_booking_params
2112
    )
2113
    assert resp.json['err_desc'] == "Person not found"
2114
    assert resp.json['err'] == 'not-found'
2115

  
2116
    Link.objects.create(resource=resource, name_id='yyy', family_id='XXX', person_id='42')
2117
    filepath = os.path.join(os.path.dirname(__file__), 'data/caluire_axel/family_info.xml')
2118
    with open(filepath) as xml:
2119
        content = xml.read()
2120
    with mock_data(content, 'GetFamilleIndividus'):
2121
        resp = app.post_json(
2122
            '/caluire-axel/test/set_activity_agenda_typical_week?NameID=yyy', params=week_booking_params
2123
        )
2124
        assert resp.json['err_desc'] == "Child not found"
2125
        assert resp.json['err'] == 'not-found'
2126

  
2127

  
2128
def test_set_activity_agenda_typical_week_endpoint_date_error(app, resource, week_booking_params):
2129
    Link.objects.create(resource=resource, name_id='yyy', family_id='XXX', person_id='42')
2130
    filepath = os.path.join(os.path.dirname(__file__), 'data/caluire_axel/family_info.xml')
2131
    with open(filepath) as xml:
2132
        content = xml.read()
2133
    with mock_data(content, 'GetFamilleIndividus'):
2134
        week_booking_params['start_date'] = '2021-09-01'
2135
        week_booking_params['end_date'] = '2021-08-31'
2136
        resp = app.post_json(
2137
            '/caluire-axel/test/set_activity_agenda_typical_week?NameID=yyy',
2138
            params=week_booking_params,
2139
            status=400,
2140
        )
2141
        assert resp.json['err_desc'] == "start_date should be before end_date"
2142
        assert resp.json['err'] == 'bad-request'
2143

  
2144
        week_booking_params['end_date'] = '2022-09-01'
2145
        resp = app.post_json(
2146
            '/caluire-axel/test/set_activity_agenda_typical_week?NameID=yyy',
2147
            params=week_booking_params,
2148
            status=400,
2149
        )
2150
        assert (
2151
            resp.json['err_desc'] == "start_date and end_date are in different reference year (2021 != 2022)"
2152
        )
2153
        assert resp.json['err'] == 'bad-request'
2154

  
2155

  
2156
def test_set_activity_agenda_typical_week_endpoint(
2157
    app, resource, family_data, activities, week_booking_params
2158
):
2159
    Link.objects.create(resource=resource, name_id='yyy', family_id='XXX', person_id='42')
2160
    with mock.patch(
2161
        'passerelle.contrib.caluire_axel.models.CaluireAxel.get_family_data',
2162
        return_value=family_data,
2163
    ):
2164
        with mock.patch(
2165
            'passerelle.contrib.caluire_axel.models.CaluireAxel.get_child_activities',
2166
            return_value=activities,
2167
        ):
2168
            with mock.patch(
2169
                'passerelle.contrib.caluire_axel.models.CaluireAxel.get_bookings',
2170
                return_value=[],
2171
            ):
2172
                resp = app.post_json(
2173
                    '/caluire-axel/test/set_activity_agenda_typical_week?NameID=yyy',
2174
                    params=week_booking_params,
2175
                )
2176
    assert resp.json['err'] == 0
2177
    assert resp.json['updated'] is True
2178
    assert resp.json['count'] == 0
2179

  
2180

  
2181
@pytest.mark.parametrize('prefill', [True, False])
2182
@freezegun.freeze_time('2020-08-01')
2183
def test_set_activity_agenda_typical_week_endpoint_prefill_periscolaire(
2184
    app, resource, family_data, week_booking_params, prefill
2185
):
2186
    Link.objects.create(resource=resource, name_id='yyy', family_id='XXX', person_id='42')
2187
    for activity_id in ['ACCMAT', 'GARDERIES', 'ETUDES', 'CANTINE', 'FOOBAR']:
2188
        activity = {
2189
            'ENTREE': '2020-09-02',
2190
            'SORTIE': '2021-08-31',
2191
            'IDENTACTIVITE': activity_id,
2192
            'LIBELLEACTIVITE': 'FOOBAR',
2193
        }
2194
        week_booking_params['booking_list'] = ['monday']
2195
        week_booking_params['activity_id'] = activity_id
2196
        with mock.patch(
2197
            'passerelle.contrib.caluire_axel.models.CaluireAxel.get_family_data',
2198
            return_value=family_data,
2199
        ):
2200
            with mock.patch(
2201
                'passerelle.contrib.caluire_axel.models.CaluireAxel.get_child_activities',
2202
                return_value={'ACTIVITE': [activity]},
2203
            ):
2204
                bookings = [
2205
                    {
2206
                        'id': '50632:%s:2020-09-07' % activity_id,
2207
                        'disabled': False,
2208
                        'prefill': prefill,
2209
                    },
2210
                    {
2211
                        'id': '50632:%s:2020-09-08' % activity_id,
2212
                        'disabled': False,
2213
                        'prefill': prefill,
2214
                    },
2215
                    {
2216
                        'id': '50632:%s:2020-09-10' % activity_id,
2217
                        'disabled': False,
2218
                        'prefill': prefill,
2219
                    },
2220
                    {
2221
                        'id': '50632:%s:2020-09-11' % activity_id,
2222
                        'disabled': False,
2223
                        'prefill': prefill,
2224
                    },
2225
                ]
2226
                with mock.patch(
2227
                    'passerelle.contrib.caluire_axel.models.CaluireAxel.get_bookings',
2228
                    return_value=bookings,
2229
                ):
2230
                    with mock.patch('passerelle.contrib.caluire_axel.schemas.set_agenda') as operation:
2231
                        operation.return_value = OperationResult(
2232
                            json_response={'DATA': {'PORTAIL': {'SETAGENDA': {'CODE': 0}}}},
2233
                            xml_request='',
2234
                            xml_response='',
2235
                        )
2236
                        resp = app.post_json(
2237
                            '/caluire-axel/test/set_activity_agenda_typical_week?NameID=yyy',
2238
                            params=week_booking_params,
2239
                        )
2240
        assert resp.json['err'] == 0
2241
        assert resp.json['updated'] is True
2242
        assert operation.call_args_list[0][0][1]['PORTAIL']['SETAGENDA']['IDENTINDIVIDU'] == '50632'
2243
        assert (
2244
            operation.call_args_list[0][0][1]['PORTAIL']['SETAGENDA']['ACTIVITE']['IDENTACTIVITE']
2245
            == activity_id
2246
        )
2247
        if prefill is True:
2248
            assert len(operation.call_args_list[0][0][1]['PORTAIL']['SETAGENDA']['ACTIVITE']['JOUR']) == 3
2249
            for i, day in enumerate(['2020-09-08', '2020-09-10', '2020-09-11']):
2250
                assert (
2251
                    operation.call_args_list[0][0][1]['PORTAIL']['SETAGENDA']['ACTIVITE']['JOUR'][i][
2252
                        'JOURDATE'
2253
                    ]
2254
                    == day
2255
                )
2256
                assert (
2257
                    operation.call_args_list[0][0][1]['PORTAIL']['SETAGENDA']['ACTIVITE']['JOUR'][i]['MATIN']
2258
                    == 'D'
2259
                )
2260
        else:
2261
            assert len(operation.call_args_list[0][0][1]['PORTAIL']['SETAGENDA']['ACTIVITE']['JOUR']) == 1
2262
            assert (
2263
                operation.call_args_list[0][0][1]['PORTAIL']['SETAGENDA']['ACTIVITE']['JOUR'][0]['JOURDATE']
2264
                == '2020-09-07'
2265
            )
2266
            assert (
2267
                operation.call_args_list[0][0][1]['PORTAIL']['SETAGENDA']['ACTIVITE']['JOUR'][0]['MATIN']
2268
                == 'X'
2269
            )
2270

  
2271

  
2272
@freezegun.freeze_time('2020-08-01')
2273
def test_set_activity_agenda_typical_week_endpoint_prefill_extrascolaire(
2274
    app,
2275
    resource,
2276
    family_data,
2277
    week_booking_params,
2278
):
2279
    Link.objects.create(resource=resource, name_id='yyy', family_id='XXX', person_id='42')
2280
    for activity_id in ['CJ MER', 'CJVACANCES']:
2281
        activity = {
2282
            'ENTREE': '2020-09-02',
2283
            'SORTIE': '2021-08-31',
2284
            'IDENTACTIVITE': activity_id,
2285
            'LIBELLEACTIVITE': 'FOOBAR',
2286
        }
2287
        week_booking_params['booking_list'] = ['monday']
2288
        week_booking_params['activity_id'] = activity_id
2289
        with mock.patch(
2290
            'passerelle.contrib.caluire_axel.models.CaluireAxel.get_family_data',
2291
            return_value=family_data,
2292
        ):
2293
            with mock.patch(
2294
                'passerelle.contrib.caluire_axel.models.CaluireAxel.get_child_activities',
2295
                return_value={'ACTIVITE': [activity]},
2296
            ):
2297
                bookings = [
2298
                    {
2299
                        'id': '50632:%s:2020-09-07' % activity_id,
2300
                        'disabled': False,
2301
                        'prefill': False,
2302
                    },
2303
                ]
2304
                with mock.patch(
2305
                    'passerelle.contrib.caluire_axel.models.CaluireAxel.get_bookings',
2306
                    return_value=bookings,
2307
                ):
2308
                    with mock.patch('passerelle.contrib.caluire_axel.schemas.set_agenda') as operation:
2309
                        operation.return_value = OperationResult(
2310
                            json_response={'DATA': {'PORTAIL': {'SETAGENDA': {'CODE': 0}}}},
2311
                            xml_request='',
2312
                            xml_response='',
2313
                        )
2314
                        resp = app.post_json(
2315
                            '/caluire-axel/test/set_activity_agenda_typical_week?NameID=yyy',
2316
                            params=week_booking_params,
2317
                            status=400,
2318
                        )
2319
    assert resp.json['err_desc'] == "Not available for this activity"
2320
    assert resp.json['err'] == 'bad-request'
2321

  
2322

  
2323
@pytest.mark.parametrize('disabled', [True, False, None])
2324
@freezegun.freeze_time('2020-08-01')
2325
def test_set_activity_agenda_typical_week_endpoint_disabled(
2326
    app, resource, family_data, week_booking_params, disabled
2327
):
2328
    Link.objects.create(resource=resource, name_id='yyy', family_id='XXX', person_id='42')
2329
    activity = {
2330
        'ENTREE': '2020-09-02',
2331
        'SORTIE': '2021-08-31',
2332
        'IDENTACTIVITE': 'FOOBAR',
2333
        'LIBELLEACTIVITE': 'FOOBAR',
2334
    }
2335
    week_booking_params['booking_list'] = ['monday']
2336
    week_booking_params['activity_id'] = 'FOOBAR'
2337
    with mock.patch(
2338
        'passerelle.contrib.caluire_axel.models.CaluireAxel.get_family_data',
2339
        return_value=family_data,
2340
    ):
2341
        with mock.patch(
2342
            'passerelle.contrib.caluire_axel.models.CaluireAxel.get_child_activities',
2343
            return_value={'ACTIVITE': [activity]},
2344
        ):
2345
            bookings = []
2346
            if disabled is not None:
2347
                bookings = [
2348
                    {
2349
                        'id': '50632:FOOBAR:2020-09-07',
2350
                        'disabled': disabled,
2351
                        'prefill': False,
2352
                    },
2353
                ]
2354
            with mock.patch(
2355
                'passerelle.contrib.caluire_axel.models.CaluireAxel.get_bookings',
2356
                return_value=bookings,
2357
            ):
2358
                with mock.patch('passerelle.contrib.caluire_axel.schemas.set_agenda') as operation:
2359
                    operation.return_value = OperationResult(
2360
                        json_response={'DATA': {'PORTAIL': {'SETAGENDA': {'CODE': 0}}}},
2361
                        xml_request='',
2362
                        xml_response='',
2363
                    )
2364
                    resp = app.post_json(
2365
                        '/caluire-axel/test/set_activity_agenda_typical_week?NameID=yyy',
2366
                        params=week_booking_params,
2367
                    )
2368
    assert resp.json['err'] == 0
2369
    assert resp.json['updated'] is True
2370
    if disabled is False:
2371
        assert operation.call_args_list[0][0][1]['PORTAIL']['SETAGENDA']['IDENTINDIVIDU'] == '50632'
2372
        assert (
2373
            operation.call_args_list[0][0][1]['PORTAIL']['SETAGENDA']['ACTIVITE']['IDENTACTIVITE'] == 'FOOBAR'
2374
        )
2375
        assert len(operation.call_args_list[0][0][1]['PORTAIL']['SETAGENDA']['ACTIVITE']['JOUR']) == 1
2376
        assert (
2377
            operation.call_args_list[0][0][1]['PORTAIL']['SETAGENDA']['ACTIVITE']['JOUR'][0]['JOURDATE']
2378
            == '2020-09-07'
2379
        )
2380
        assert (
2381
            operation.call_args_list[0][0][1]['PORTAIL']['SETAGENDA']['ACTIVITE']['JOUR'][0]['MATIN'] == 'X'
2382
        )
2383
    else:
2384
        assert len(operation.call_args_list) == 0
2385

  
2386

  
2387
@pytest.mark.parametrize('code', [-1, -2, -3, -4])
2388
def test_set_activity_agenda_typical_week_endpoint_wrong_code(
2389
    app, resource, family_data, activities, week_booking_params, code
2390
):
2391
    Link.objects.create(resource=resource, name_id='yyy', family_id='XXX', person_id='42')
2392
    bookings = [
2393
        {
2394
            'id': '50632:ELEM:2020-09-07',
2395
            'disabled': False,
2396
            'prefill': True,
2397
        },
2398
    ]
2399
    content = (
2400
        '''<PORTAIL>
2401
    <SETAGENDA>
2402
        <CODE>%s</CODE>
2403
    </SETAGENDA>
2404
</PORTAIL>'''
2405
        % code
2406
    )
2407
    with mock_data(content, 'SetAgenda', data_method='setData'):
2408
        with mock.patch(
2409
            'passerelle.contrib.caluire_axel.models.CaluireAxel.get_family_data',
2410
            return_value=family_data,
2411
        ):
2412
            with mock.patch(
2413
                'passerelle.contrib.caluire_axel.models.CaluireAxel.get_child_activities',
2414
                return_value=activities,
2415
            ):
2416
                with mock.patch(
2417
                    'passerelle.contrib.caluire_axel.models.CaluireAxel.get_bookings',
2418
                    return_value=bookings,
2419
                ):
2420
                    resp = app.post_json(
2421
                        '/caluire-axel/test/set_activity_agenda_typical_week?NameID=yyy',
2422
                        params=week_booking_params,
2423
                    )
2424
    assert resp.json['err_desc'] == "Wrong agenda status"
2425
    assert resp.json['err'] == 'agenda-code-error-%s' % code
2426

  
2427

  
2023 2428
def test_invoices_endpoint_axel_error(app, resource):
2024 2429
    Link.objects.create(resource=resource, name_id='yyy', family_id='XXX', person_id='42')
2025 2430
    with mock.patch('passerelle.contrib.caluire_axel.schemas.get_factures_a_payer') as operation:
2026
-