Projet

Général

Profil

0001-workflows-add-some-options-to-add-attachement-action.patch

Emmanuel Cazenave, 03 septembre 2020 13:20

Télécharger (12,2 ko)

Voir les différences:

Subject: [PATCH] workflows: add some options to add attachement action
 (#37860)

 tests/test_form_pages.py | 41 ++++++++++++++++++++++++++++++++----
 wcs/fields.py            | 45 +++++-----------------------------------
 wcs/qommon/misc.py       | 41 ++++++++++++++++++++++++++++++++++++
 wcs/wf/attachment.py     | 27 +++++++++++++++++++++---
 4 files changed, 107 insertions(+), 47 deletions(-)
tests/test_form_pages.py
3419 3419
    resp = resp.follow()
3420 3420
    assert 'The form has been recorded' in resp.text
3421 3421

  
3422
    resp.forms[0]['attachment_attach'] = Upload('test.txt', b'foobar', 'text/plain')
3422
    resp.forms[0]['attachment_attach$file'] = Upload('test.txt', b'foobar', 'text/plain')
3423 3423
    resp = resp.forms[0].submit('button_attach')
3424 3424

  
3425 3425
    assert formdef.data_class().count() == 1
......
3463 3463
    resp = resp.follow()
3464 3464
    assert 'The form has been recorded' in resp.text
3465 3465

  
3466
    resp.forms[0]['attachment_attach'] = Upload('test.txt', b'foobar', 'text/plain')
3466
    resp.forms[0]['attachment_attach$file'] = Upload('test.txt', b'foobar', 'text/plain')
3467 3467
    resp = resp.forms[0].submit('button_attach')
3468 3468

  
3469 3469
    assert formdef.data_class().count() == 1
......
3529 3529
    resp = resp.follow()
3530 3530
    assert 'The form has been recorded' in resp.text
3531 3531

  
3532
    resp.forms[0]['attachment_attach'] = Upload('test.txt', b'foobar', 'text/plain')
3532
    resp.forms[0]['attachment_attach$file'] = Upload('test.txt', b'foobar', 'text/plain')
3533 3533
    resp = resp.forms[0].submit('button_attach')
3534 3534

  
3535 3535
    # backoffice file field is set
......
3581 3581
    resp = resp.follow()
3582 3582
    assert 'The form has been recorded' in resp.text
3583 3583

  
3584
    resp.forms[0]['attachment_attach'] = Upload('test.txt', b'foobar', 'text/plain')
3584
    resp.forms[0]['attachment_attach$file'] = Upload('test.txt', b'foobar', 'text/plain')
3585 3585
    resp = resp.forms[0].submit('button_attach')
3586 3586

  
3587 3587
    # backoffice file field is set
......
3598 3598
        assert not evo.parts
3599 3599

  
3600 3600

  
3601
def test_formdata_attachment_file_options(pub):
3602
    create_user(pub)
3603
    wf = Workflow(name='status')
3604
    st1 = wf.add_status('Status1', 'st1')
3605
    attach = AddAttachmentWorkflowStatusItem()
3606
    attach.id = '_attach'
3607
    attach.by = ['_submitter']
3608
    attach.document_type = {'label': 'Fichiers vidéo', 'mimetypes': ['video/*'], 'id': '_video'}
3609
    attach.max_file_size = '3Mo'
3610

  
3611
    st1.items.append(attach)
3612
    attach.parent = st1
3613
    wf.store()
3614

  
3615
    formdef = create_formdef()
3616
    formdef.workflow_id = wf.id
3617
    formdef.fields = []
3618
    formdef.store()
3619
    formdef.data_class().wipe()
3620

  
3621
    resp = login(get_app(pub), username='foo', password='foo').get('/test/')
3622
    resp = resp.forms[0].submit('submit')
3623
    assert 'Check values then click submit.' in resp.text
3624
    resp = resp.forms[0].submit('submit')
3625
    assert resp.status_int == 302
3626
    resp = resp.follow()
3627
    assert 'The form has been recorded' in resp.text
3628

  
3629
    file_input = resp.forms[0]['attachment_attach$file']
3630
    assert file_input.attrs['accept'] == 'video/*'
3631
    assert file_input.attrs['data-max-file-size'] == '3000000'
3632

  
3633

  
3601 3634
def test_formdata_generated_document_download(pub):
3602 3635
    create_user(pub)
3603 3636
    wf = Workflow(name='status')
wcs/fields.py
38 38
from .qommon import _, N_, force_str
39 39
from .qommon import evalutils
40 40
from .qommon.form import *
41
from .qommon.misc import localstrftime, strftime, date_format, ellipsize, xml_node_text, get_as_datetime
41
from .qommon.misc import localstrftime, strftime, date_format, ellipsize, xml_node_text, get_as_datetime, get_document_types, get_document_type_value_options
42 42
from .qommon.ods import NS as OD_NS, clean_text as od_clean_text
43 43
from .qommon.template import Template, TemplateError
44 44
from .qommon import get_cfg, get_logger
......
1067 1067

  
1068 1068
    def fill_admin_form(self, form):
1069 1069
        WidgetField.fill_admin_form(self, form)
1070
        document_types = self.get_document_types()
1071
        cur_dt = self.document_type or {}
1072
        # SingleSelectWidget compare the value and not the keys, so if we want
1073
        # the current value not to be hidden, we must reset it with the corresponding
1074
        # value from settings based on the 'id'
1075
        document_type_id = cur_dt.get('id')
1076
        if document_type_id in document_types \
1077
               and cur_dt != document_types[document_type_id]:
1078
            cur_dt = document_types[document_type_id]
1079
        options = [(None, '---', {})]
1080
        options += [(doc_type, doc_type['label'], key) for key, doc_type in document_types.items()]
1070
        value, options = get_document_type_value_options(self.document_type)
1081 1071
        form.add(SingleSelectWidget, 'document_type', title=_('File type suggestion'),
1082
                value=cur_dt, options=options,
1083
                advanced=not(cur_dt))
1072
                value=value, options=options,
1073
                advanced=not(value))
1084 1074
        form.add(FileSizeWidget, 'max_file_size', title=_('Max file size'),
1085 1075
                value=self.max_file_size,
1086 1076
                advanced=not(self.max_file_size))
......
1215 1205
            if value and hasattr(value, 'token'):
1216 1206
                get_request().form[self.field_key + '$token'] = value.token
1217 1207

  
1218
    def get_document_types(self):
1219
        document_types = {
1220
            '_audio': {
1221
                'label': _('Sound files'),
1222
                'mimetypes': ['audio/*'],
1223
            },
1224
            '_video': {
1225
                'label': _('Video files'),
1226
                'mimetypes': ['video/*'],
1227
            },
1228
            '_image': {
1229
                'label': _('Image files'),
1230
                'mimetypes': ['image/*'],
1231
            }
1232
        }
1233
        # Local document types
1234
        document_types.update(get_cfg('filetypes', {}))
1235
        for key, document_type in document_types.items():
1236
            document_type['id'] = key
1237
        # add current file type if it does not exist anymore in the settings
1238
        cur_dt = self.document_type or {}
1239
        if cur_dt and cur_dt['id'] not in document_types:
1240
            document_types[cur_dt['id']] = cur_dt
1241
        return document_types
1242

  
1243 1208
    def migrate(self):
1244 1209
        changed = super(FileField, self).migrate()
1245 1210
        if 'file_type' in self.__dict__:
1246 1211
            self.document_type = {}
1247 1212
            if self.__dict__['file_type']:
1248 1213
                file_type = self.__dict__['file_type']
1249
                document_types = self.get_document_types()
1214
                document_types = get_document_types(self.document_type)
1250 1215
                parts = []
1251 1216
                for key, value in document_types.items():
1252 1217
                    if file_type == value.get('mimetypes'):
wcs/qommon/misc.py
837 837

  
838 838
    def _q_traverse(self, path):
839 839
        return redirect(self.url)
840

  
841

  
842
def get_document_types(document_type):
843
    document_types = {
844
        '_audio': {
845
            'label': _('Sound files'),
846
            'mimetypes': ['audio/*'],
847
        },
848
        '_video': {
849
            'label': _('Video files'),
850
            'mimetypes': ['video/*'],
851
        },
852
        '_image': {
853
            'label': _('Image files'),
854
            'mimetypes': ['image/*'],
855
        }
856
    }
857
    # Local document types
858
    document_types.update(get_cfg('filetypes', {}))
859
    for key, document_type in document_types.items():
860
        document_type['id'] = key
861
            # add current file type if it does not exist anymore in the settings
862
    cur_dt = document_type or {}
863
    if cur_dt and cur_dt['id'] not in document_types:
864
        document_types[cur_dt['id']] = cur_dt
865
    return document_types
866

  
867

  
868
def get_document_type_value_options(document_type):
869
    document_types = get_document_types(document_type)
870
    cur_dt = document_type or {}
871
    # SingleSelectWidget compare the value and not the keys, so if we want
872
    # the current value not to be hidden, we must reset it with the corresponding
873
    # value from settings based on the 'id'
874
    document_type_id = cur_dt.get('id')
875
    if document_type_id in document_types \
876
           and cur_dt != document_types[document_type_id]:
877
        cur_dt = document_types[document_type_id]
878
    options = [(None, '---', {})]
879
    options += [(doc_type, doc_type['label'], key) for key, doc_type in document_types.items()]
880
    return cur_dt, options
wcs/wf/attachment.py
20 20

  
21 21
from ..qommon import _, N_
22 22
from wcs.workflows import *
23
from ..qommon import get_cfg
23 24
from ..qommon.errors import *
25
from ..qommon.misc import get_document_type_value_options
24 26

  
25 27
from wcs.forms.common import FormStatusPage, FileDirectory
26 28
from wcs.portfolio import has_portfolio, push_document
......
86 88
    backoffice_filefield_id = None
87 89
    attach_to_history = True  # legacy choice
88 90
    push_to_portfolio = False
91
    document_type = None
92
    max_file_size = None
93

  
94
    def __init__(self, *args, **kwargs):
95
        super(AddAttachmentWorkflowStatusItem, self).__init__(*args, **kwargs)
96
        self.document_type = self.document_type or {}
89 97

  
90 98
    @classmethod
91 99
    def init(cls):
......
106 114
            title = self.title or _('Upload File')
107 115
        else:
108 116
            title = None
109
        form.add(FileWidget, 'attachment%s' % self.id, title=title,
110
                    required=self.required, hint=self.hint)
117
        file_type = self.document_type.get('mimetypes')
118
        form.add(FileWithPreviewWidget, 'attachment%s' % self.id, title=title,
119
                    required=self.required, hint=self.hint, file_type=file_type,
120
                    max_file_size=self.max_file_size)
111 121
        if self.display_button:
112 122
            form.add_submit('button%s' % self.id, self.button_label or _('Upload File'))
113 123
            form.get_widget('button%s' % self.id).backoffice_info_text = self.backoffice_info_text
......
139 149
    def get_parameters(self):
140 150
        parameters = ('by', 'required', 'title', 'display_title', 'button_label',
141 151
                'display_button', 'hint', 'backoffice_info_text',
142
                'backoffice_filefield_id', 'varname', 'attach_to_history')
152
                'backoffice_filefield_id', 'varname', 'attach_to_history', 'document_type',
153
                'max_file_size')
143 154
        if has_portfolio():
144 155
            parameters += ('push_to_portfolio',)
145 156
        parameters += ('condition',)
......
191 202
            form.add(CheckboxWidget, '%spush_to_portfolio' % prefix,
192 203
                     title=_('Push to portfolio'),
193 204
                     value=self.push_to_portfolio)
205
        if 'document_type' in parameters:
206
            value, options = get_document_type_value_options(self.document_type)
207
            form.add(SingleSelectWidget, 'document_type', title=_('File type suggestion'),
208
                     value=value, options=options,
209
                     advanced=not(value))
210
        if 'max_file_size' in parameters:
211
            form.add(FileSizeWidget, 'max_file_size', title=_('Max file size'),
212
                     value=self.max_file_size,
213
                     advanced=not(self.max_file_size))
214

  
194 215

  
195 216

  
196 217
register_item_class(AddAttachmentWorkflowStatusItem)
197
-