source: LATMOS-Accounts-Web/lib/LATMOS/Accounts/Web/Model/AttrForms.pm @ 951

Last change on this file since 951 was 951, checked in by nanardon, 12 years ago
  • use js to add values on multi-valuable attribute
File size: 17.5 KB
Line 
1package LATMOS::Accounts::Web::Model::AttrForms;
2
3use strict;
4use warnings;
5use base 'Catalyst::Model';
6use LATMOS::Accounts::Log;
7
8=head1 NAME
9
10LATMOS::Accounts::Web::Model::AttrForms - Catalyst Model
11
12=head1 DESCRIPTION
13
14Catalyst Model.
15
16=cut
17
18my $forms = {
19    usersys => {
20        name => 'SystÚme',
21        attrs => [ qw(
22            sn givenName description
23            uid uidNumber gidNumber gecos homeDirectory loginShell
24            mail initials nickname
25            expire
26            locked
27            create
28            date
29        ) ],
30    },
31    user => {
32        name => 'Statut',
33        attrs => [ qw(
34            sn givenName description
35            company
36            department
37            manager
38            managerContact
39            contratType
40            expire
41            snNative
42            givenNameNative
43            wWWHomePage
44            halReference
45            create
46            date
47        ) ],
48    },
49    useraddress => {
50        name => 'Adresse',
51        attrs => [ qw(
52            initials
53            mail
54        ) ],
55    },
56    usermy => {
57        name => 'My',
58        attrs => [ qw(
59            snNative
60            givenNameNative
61            wWWHomePage
62            halReference
63        ) ],
64    },
65    site => {
66        name => 'Site',
67        attrs => [ qw(
68            description
69            siteNick
70            streetAddress
71            postOfficeBox
72            postalCode
73            l
74            st
75            co
76            facsimileTelephoneNumber
77            create
78            date
79        ) ],
80    },
81    address => {
82        name => 'Adresse',
83        attrs => [ qw(
84            isMainAddress
85            telephoneNumber
86            streetAddress
87            postOfficeBox
88            postalCode
89            l
90            st
91            physicalDeliveryOfficeName
92            site
93            co
94            unexported
95            description
96        ) ],
97    },
98    group => {
99        name => 'SystÚme',
100        attrs => [ qw(
101            gidNumber description
102            managedBy
103            sutype
104            create
105            date
106        ) ],
107    },
108    nethost => {
109        name => 'Ordinateur',
110        attrs => [ qw(
111            name
112            description
113            serialNumber
114            owner
115            user
116            ip
117            macaddr
118            noDynamic
119            cname
120            otherName
121            reverse
122            create
123            date
124            unexported
125        ) ],
126    },
127    netzone => {
128        name => 'Zone réseau',
129        attrs => [ qw(
130            name
131            description
132            type
133            net
134            netExclude
135            outputD
136            templateD
137            site
138            allow_dyn
139            dynFrom
140            domain
141            ipCount
142            freeIPCount
143            create
144            date
145            dnsRevision
146            lastUpdate
147            unexported
148        ) ],
149    },
150    aliases => {
151        name => 'Alias mail',
152        attrs => [ qw(
153            forward
154            expire
155            finalpoint
156            parents
157            created
158            date
159            unexported
160        )],
161    },
162};
163
164sub escape {
165    my ($self, $text) = @_;
166    $text ||= '';
167    for ($text) {
168        s/&/&/g;
169        s/</&lt;/g;
170        s/>/&gt;/g;
171        s/"/&quot;/g;
172    }
173    $text;
174}
175
176sub new {
177    my ($class) = @_;
178    bless({}, $class);
179}
180
181# call either OBJ or type + base
182
183sub ACCEPT_CONTEXT {
184    my ($self, $c, $form, $object, $base) = @_;
185    my $new = {};
186    $new->{c} = $c;
187    $new->{form} = $form;
188    $new->{object} = $object if (ref $object);
189    $new->{base} = $base || ($object ? $object->base : undef) or return $self;
190    $new->{otype} = ref $object ? $object->type : $object;
191    bless($new, __PACKAGE__);
192}
193
194sub base {
195    my ( $self ) = @_;
196    $self->{base}
197}
198
199sub otype {
200    my ($self) = @_;
201    $self->{otype};
202}
203
204sub label {
205    my ($self) = @_;
206    $forms->{$self->{form}}->{name} || ''
207}
208
209sub attributes {
210    my ($self, $for) = @_;
211    grep { $_ }
212    grep { $self->base->attribute($self->otype, $_) }
213    @{ $forms->{$self->{form}}->{attrs} };
214}
215
216sub attr_label {
217    my ($self, $attr) = @_;
218    my ($hint, $label) = ('', '');
219    LATMOS::Accounts::Web->config->{attrs} ||= {};
220    my $htmlname = ($self->{object} ? $self->{object}->id . '_' : '') . $attr;
221    if (my $attr_config = LATMOS::Accounts::Web->config->{attrs}{$attr}) {
222        $label = $attr_config->{label} || '';
223        #utf8::is_utf8($label) && utf8::encode($label);
224        $hint = $attr_config->{hint} || '';
225        #utf8::is_utf8($hint) && utf8::encode($hint);
226    }
227    return sprintf('<label %sfor="%s">%s</label>',
228        ($hint ? sprintf('title="%s"', $self->escape($hint)) : ''),
229        $self->escape($htmlname),
230        $self->escape($label || $attr),
231    );
232}
233
234sub attr_hint {
235    my ($self, $attr) = @_;
236    LATMOS::Accounts::Web->config->{attrs} ||= {};
237    if (my $attr_config = LATMOS::Accounts::Web->config->{attrs}{$attr}) {
238        return $attr_config->{hint} || '';
239    }
240    return;
241}
242
243sub attr_raw_value {
244    my ($self, $attr) = @_;
245    return $self->{c}->req->param($attr) ||
246        ($self->{object} ? $self->{object}->get_attributes($attr) : '')
247}
248
249sub attr_field_name {
250    my ($self, $attr) = @_;
251    my $id = $self->{object}
252        ? $self->{object}->id . '_'
253        : '';
254    $id =~ s/\./_/g;
255    $id . $attr;
256}
257
258sub attr_field {
259    my ($self, $attr, $type) = @_;
260
261    my $attr_info = $type
262        ? { formtype => $type }
263        : undef;
264
265    my $attribute = ($self->{object}
266        ? $self->{object}->attribute($attr)
267        : $self->base->attribute($self->otype, $attr));
268
269    $attribute ||= $self->base->attribute(
270        $self->otype,
271        { 
272            name => $attr,
273            formtype => $type
274        },
275    );
276
277    my $htmlname = $self->escape($self->attr_field_name($attr));
278
279    my @html_fields;
280    foreach my $attr_raw_value (
281        $attribute->{multiple}
282            ? ((grep { $_ } $self->attr_raw_value($attr)),
283                $attribute->readonly
284                    ? ()
285                    : ('')
286            )
287            : ($self->attr_raw_value($attr))) {
288
289        my $html_id = $htmlname .
290            (scalar(@html_fields) ? scalar(@html_fields) : '');
291        $html_id .= 'NB' if ($attribute->multiple);
292
293        my $html_field = '';
294        my $html_ref = '';
295        for ($attribute->form_type) {
296            /^textarea$/i and do {
297                $html_field = sprintf(
298                    '<textarea id="%s" name="%s" cols="40">%s</textarea>',
299                    $self->escape($html_id),
300                    $self->escape($htmlname),
301                    $self->escape($attr_raw_value || ''),
302                );
303                last;
304            };
305            /^label$/i and do {
306                $attr_raw_value or last;
307                $html_field = $self->escape($attr_raw_value);
308                $html_field =~ s/\n/<br>/g;
309                $html_field .= sprintf('<input type="hidden" name="%s" value="%s">',
310                    $self->escape($htmlname), ($attr_raw_value || ''));
311                last;
312            };
313            /^date$/i and do {
314                my ($date, $time) = split(/ /, $self->attr_raw_value($attr) || '');
315                if ($date && $date =~ /^(\d+)-(\d+)-(\d+)$/) {
316                    $date = "$3/$2/$1";
317                }
318                my $html = "\n" . q{<SCRIPT LANGUAGE="JavaScript" ID="js13">
319                var cal13 = new CalendarPopup();
320                </SCRIPT>} . "\n";
321                $html .= sprintf(
322                    '<input type="text" id="%s" name="%s" value="%s" size="12">',
323                    $self->escape($html_id),
324                    $self->escape($htmlname),
325                    $self->escape($date)
326                );
327                $html .= q{<DIV ID="testdiv1" STYLE="position:absolute;visibility:hidden;background-color:white;layer-background-color:white;"></DIV>};
328                $html .= qq|
329                <A HREF="#"
330                    onClick="cal13.select(document.getElementById('$html_id'),'${html_id}_anc','dd/MM/yyyy');return false;"
331                    TITLE="Date"
332                    NAME="${html_id}_anc" ID="${html_id}_anc">
333                    <img class="attr" src="| . $self->{c}->uri_for(qw(/static icons view-calendar-day.png))
334                    . qq{" style="ref"></A>
335                    } . "\n";
336                $html_field = $html;
337                last;
338            };
339            /^checkbox(?::(\w+))?$/i and do {
340                my $options = $1 || '';
341                $html_field = sprintf('<input type="checkbox" name="%s"%s>',
342                    $self->escape($htmlname),
343                    $attr_raw_value ? '  checked="yes"' : ''
344                ); 
345                $html_field .= sprintf('<input type="hidden" name="%s">',
346                    $self->escape($htmlname));
347                if ($attribute->form_option('rawvalue')) {
348                    $html_field .= $attr_raw_value
349                        ? ' ' . $attr_raw_value
350                        : ''; 
351                }
352                last;
353            };
354            /^LIST/ and do {
355                my $options = $1 || '';
356                my $select = sprintf('<select id="%s" name="%s">',
357                    $self->escape($html_id),
358                    $self->escape($htmlname)) . "\n";
359                $select .= '<option value="">--</option>' . "\n"
360                    unless($attribute->mandatory);
361                my $value = $attr_raw_value || '';
362                my $initial_observed = '';
363                my @valslist;
364                foreach my $val (sort $attribute->can_values) {
365                    push(@valslist, {
366                        val => $val,
367                        disp => $attribute->display($val || ''),
368                    });
369                }
370                foreach (sort { $a->{disp} cmp $b->{disp} } @valslist) {
371                    $select .= sprintf(
372                        '    <option value="%s"%s>%s</option>',
373                        $self->escape($_->{val} || ''),
374                        $value eq $_->{val} ? ' selected="selected"' : '',
375                        $self->escape($_->{disp} || ''),
376                    );
377                    $select .= "\n";
378                }
379                $select .= "</select>\n";
380
381                $html_field = $select;
382                last;
383            };
384            /^text(-\w+)?(?::(\d+))?/i and do {
385                my $flag = $1 || '';
386                $html_field = sprintf(
387                    '<input type="text" id="%s" name="%s" value="%s" size="%d">',
388                    $self->escape($html_id),
389                    $self->escape($htmlname),
390                    $self->escape($attr_raw_value),
391                    $attribute->form_option('length') || 30,
392                );
393                if ($flag =~ /A/) {
394                    $html_field .= qq|<span id="${html_id}_auto_complete"></span>|;
395                    $html_field .= "\n";
396                    $html_field .= $self->{c}->prototype->auto_complete_field(
397                        $html_id,
398                        {
399                            update => "${html_id}_auto_complete",
400                            url => $self->{c}->uri_for('/ajax', 'attrvalues', $self->otype, $attr),
401                            indicator => "${html_id}_stat", min_chars => 1,
402                            with => "'val='+document.getElementById('$html_id').value",
403                            frequency => 2,
404                        }
405                    );
406                }
407                if ($attribute->uniq) {
408                    $html_ref .= qq|<span class="inputvalidate" id="${html_id}_observer_uniq"></span>|;
409                    $html_ref .= "\n";
410                    $html_ref .= $self->{c}->prototype->observe_field(
411                        $html_id,
412                        {
413                            update => "${html_id}_observer_uniq",
414                            url => $self->{c}->uri_for('/ajax', 'objattrexist',
415                                $self->otype, $attr),
416                            frequency => 2,
417                            indicator => "${html_id}_stat", min_chars => 1,
418                            with => "'val='+document.getElementById('$html_id').value" .
419                            ($self->{object} ? "+'&exclude=" . $self->{object}->id . "'" :
420                                ''),
421                        }
422                    );
423                    $html_ref .= qq|<span style="display:none" id="${html_id}_stat">Searching...</span>|;
424                }
425                last;
426            };
427        }
428        if (my $ref = $attribute->reference) {
429            my $uri_part= {
430                user => 'users',
431                group => 'groups',
432                nethost => 'nethosts',
433                netzone => 'netzones',
434                site => 'sites'
435            }->{$ref};
436            my $text;
437            if ($self->base->attribute($ref, 'displayName')) {
438                if ($attr_raw_value &&
439                    (my $obj = $self->base->get_object($ref, $attr_raw_value)))
440                {
441                    $text = $obj->get_attributes('displayName');
442                }
443               
444                $html_ref .= $self->{c}->prototype->observe_field( $html_id, {
445                        update => "${html_id}_span",
446                        url => $self->{c}->uri_for('/ajax', 'rawattr', $ref),
447                        frequency => 1,
448                        with   => "'attr=displayName" .
449                        "&id=' + element.options[element.selectedIndex].text",
450                    }) . "\n" if ($attribute->form_type =~ /list/i);
451            } elsif($attr_raw_value && $uri_part) {
452                $text = sprintf(
453                    '<img class="attr" src="%s" title="%s">',
454                    $self->{c}->uri_for('/static', 'icons', 'arrow-right.png'),
455                    $attr_raw_value,
456                )
457            }
458            $html_ref .= sprintf(qq{<span id="%s" style="margin-left: 1em">},
459                "${html_id}_span");
460
461            if (defined($text)) {
462                $html_ref .= $uri_part
463                    ? sprintf('<a href="%s">%s</a>',
464                        $self->{c}->uri_for("/$uri_part", $attribute->display($attr_raw_value)),
465                        $text,)
466                    : $text;
467            }
468
469            $html_ref .= "</span>\n";
470        }
471        push(@html_fields, $html_field . $html_ref);
472        if ($attribute->{multiple} && (!$attr_raw_value)) {
473            my $esc_html_field = $html_field;
474            my $esc_html_ref = $html_ref;
475            $esc_html_ref =~ s/'/\\'/g;
476            #$esc_html_field =~ s/"/\\"/g;
477            my $addempty = sprintf(
478                '<div id="%s"></div>',
479                "${html_id}_mul_emp0",
480            );
481            $addempty .= sprintf(qq#
482            <script type="text/javascript">
483                var cn_${html_id} = 0;
484                function add_${html_id} () {
485                    cn_${html_id}++;
486                    var cn = cn_${html_id};
487                    var htmlid = '${html_id}'.replace(/NB/g, cn);
488                    document.getElementById('${html_id}_mul_emp' + (cn - 1)).innerHTML +=
489                        '%s<span class="inputvalidate" id="${html_id}_observer_uniq"></span><br>'.replace(/NB/g, cn);
490                    document.getElementById('${html_id}_mul_emp' + (cn - 1)).innerHTML +=
491                        '<div id="${html_id}_mul_emp' + cn + '"></div>';
492
493                    new Form.Element.Observer( '${html_id}'.replace('NB', cn),
494                           2,
495                           function( element, value ) {
496                                new Ajax.Updater( '${html_id}_observer_uniq'.replace(/NB/g, cn),
497                                    'http://localhost:8080/ajax/objattrexist/nethost/cname',
498                                    { parameters: 'val='+document.getElementById(htmlid).value+'&exclude=$attr_raw_value',asynchronous: 1 } )
499                            } );
500                }
501            </script>
502            <button type="button" onclick="add_${html_id}()">+</button>
503            #,
504            $esc_html_field
505            );
506            push(@html_fields, $addempty);
507        }
508    }
509    return join("<br>\n", @html_fields);
510}
511
512sub submit {
513    my ($self) = @_;
514    return sprintf(
515        '<input type="submit" name="%s" value="Enregistrer">',
516        $self->escape($self->label),
517    );
518}
519
520sub write_attributes {
521    my ($self) = @_;
522    my @attrs;
523    foreach ($self->attributes) {
524        my $attr = ($self->{object}
525            ? $self->{object}->attribute($_)
526            : $self->base->attribute($self->otype, $_)) or next;
527        $attr->readonly and next;
528        push(@attrs, $_);
529    }
530    @attrs;
531}
532
533sub set_attrs {
534    my ($self, $attrs) = @_;
535    $self->{c}->req->param($self->label) || $attrs or return;
536    my $prefix = $self->attr_field_name('');
537    my %fields;
538    foreach ($attrs ? @{ $attrs } : $self->write_attributes) {
539        my $attr = ($self->{object}
540            ? $self->{object}->attribute($_)
541            : $self->base->attribute($self->otype, $_)) or next;
542        if ($attr->{multiple}) {
543            $fields{$_} = [ grep { $_ } $self->{c}->req->param("$prefix$_") ];
544        } else {
545            $fields{$_} = $self->{c}->req->param("$prefix$_");
546        }
547    }
548    $self->{object}->set_c_fields(%fields) or do {
549        $self->{c}->stash->{page}{error} =
550            LATMOS::Accounts::Log::lastmessage(LA_ERR);
551        $self->{object}->base->rollback;
552        return;
553    };
554    $self->{object}->base->commit;
555}
556
557=head1 AUTHOR
558
559Thauvin Olivier
560
561=head1 LICENSE
562
563This library is free software, you can redistribute it and/or modify
564it under the same terms as Perl itself.
565
566=cut
567
5681;
Note: See TracBrowser for help on using the repository browser.