Bug 17600: Standardize our EXPORT_OK
[koha.git] / tools / modborrowers.pl
1 #!/usr/bin/perl
2
3 # Copyright 2012 BibLibre
4 #
5 # This file is part of Koha.
6 #
7 # Koha is free software; you can redistribute it and/or modify it
8 # under the terms of the GNU General Public License as published by
9 # the Free Software Foundation; either version 3 of the License, or
10 # (at your option) any later version.
11 #
12 # Koha is distributed in the hope that it will be useful, but
13 # WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 # GNU General Public License for more details.
16 #
17 # You should have received a copy of the GNU General Public License
18 # along with Koha; if not, see <http://www.gnu.org/licenses>.
19
20 # modborrowers.pl
21 #
22 # Batch Edit Patrons
23 # Modification for patron's fields:
24 # surname firstname branchcode categorycode city state zipcode country sort1
25 # sort2 dateenrolled dateexpiry borrowernotes
26 # And for patron attributes.
27
28 use Modern::Perl;
29 use CGI qw ( -utf8 );
30 use C4::Auth qw( get_template_and_user );
31 use C4::Koha qw( GetAuthorisedValues );
32 use C4::Members;
33 use C4::Output qw( output_html_with_http_headers );
34 use Koha::DateUtils qw( dt_from_string );
35 use Koha::List::Patron qw( GetPatronLists );
36 use Koha::Libraries;
37 use Koha::Patron::Categories;
38 use Koha::Patron::Debarments qw( AddDebarment DelDebarment GetDebarments );
39 use Koha::Patrons;
40
41 my $input = CGI->new;
42 my $op = $input->param('op') || 'show_form';
43 my ( $template, $loggedinuser, $cookie ) = get_template_and_user(
44     {   template_name   => "tools/modborrowers.tt",
45         query           => $input,
46         type            => "intranet",
47         flagsrequired   => { tools => "edit_patrons" },
48     }
49 );
50
51 my $logged_in_user = Koha::Patrons->find( $loggedinuser );
52
53 my %cookies   = parse CGI::Cookie($cookie);
54 my $sessionID = $cookies{'CGISESSID'}->value;
55 my $dbh       = C4::Context->dbh;
56
57 # Show borrower informations
58 if ( $op eq 'show' ) {
59     my $filefh         = $input->upload('uploadfile');
60     my $filecontent    = $input->param('filecontent');
61     my $patron_list_id = $input->param('patron_list_id');
62     my @borrowers;
63     my @cardnumbers;
64     my @notfoundcardnumbers;
65
66     # Get cardnumbers from a file or the input area
67     if ($filefh) {
68         while ( my $content = <$filefh> ) {
69             $content =~ s/[\r\n]*$//g;
70             push @cardnumbers, $content if $content;
71         }
72     } elsif ( $patron_list_id ) {
73         my ($list) = GetPatronLists( { patron_list_id => $patron_list_id } );
74
75         @cardnumbers =
76           $list->patron_list_patrons()->search_related('borrowernumber')
77           ->get_column('cardnumber')->all();
78
79     } else {
80         if ( my $list = $input->param('cardnumberlist') ) {
81             push @cardnumbers, split( /\s\n/, $list );
82         }
83     }
84
85     my $max_nb_attr = 0;
86     for my $cardnumber ( @cardnumbers ) {
87         my $patron = Koha::Patrons->find( { cardnumber => $cardnumber } );
88         if ( $patron ) {
89             if ( $logged_in_user->can_see_patron_infos( $patron ) ) {
90                 my $borrower = $patron->unblessed;
91                 my $attributes = $patron->extended_attributes;
92                 $borrower->{patron_attributes} = $attributes->as_list;
93                 $borrower->{patron_attributes_count} = $attributes->count;
94                 $max_nb_attr = $borrower->{patron_attributes_count} if $borrower->{patron_attributes_count} > $max_nb_attr;
95                 push @borrowers, $borrower;
96             } else {
97                 push @notfoundcardnumbers, $cardnumber;
98             }
99         } else {
100             push @notfoundcardnumbers, $cardnumber;
101         }
102     }
103
104     # Just for a correct display
105     for my $borrower ( @borrowers ) {
106         my $length = $borrower->{patron_attributes_count};
107         push @{ $borrower->{patron_attributes} }, {} for ( $length .. $max_nb_attr - 1);
108     }
109
110     # Construct the patron attributes list
111     my @patron_attributes_values;
112     my @patron_attributes_codes;
113     my $library_id = C4::Context->userenv ? C4::Context->userenv->{'branch'} : undef;
114     my $patron_attribute_types = Koha::Patron::Attribute::Types->search_with_library_limits({}, {}, $library_id);
115     my @patron_categories = Koha::Patron::Categories->search_with_library_limits({}, {order_by => ['description']});
116     while ( my $attr_type = $patron_attribute_types->next ) {
117         # TODO Repeatable attributes are not correctly managed and can cause data lost.
118         # This should be implemented.
119         next if $attr_type->repeatable;
120         next if $attr_type->unique_id; # Don't display patron attributes that must be unqiue
121         my $options = $attr_type->authorised_value_category
122             ? GetAuthorisedValues( $attr_type->authorised_value_category )
123             : undef;
124         push @patron_attributes_values,
125             {
126                 attribute_code => $attr_type->code,
127                 options        => $options,
128             };
129
130         my $category_code = $attr_type->category_code;
131         my ( $category_lib ) = map {
132             ( defined $category_code and $attr_type->category_code eq $category_code ) ? $attr_type->description : ()
133         } @patron_categories;
134         push @patron_attributes_codes,
135             {
136                 attribute_code => $attr_type->code,
137                 attribute_lib  => $attr_type->description,
138                 category_lib   => $category_lib,
139                 type           => $attr_type->authorised_value_category ? 'select' : 'text',
140             };
141     }
142
143     my @attributes_header = ();
144     for ( 1 .. scalar( $max_nb_attr ) ) {
145         push @attributes_header, { attribute => "Attributes $_" };
146     }
147     $template->param( borrowers => \@borrowers );
148     $template->param( attributes_header => \@attributes_header );
149     @notfoundcardnumbers = map { { cardnumber => $_ } } @notfoundcardnumbers;
150     $template->param( notfoundcardnumbers => \@notfoundcardnumbers )
151         if @notfoundcardnumbers;
152
153     # Construct drop-down list values
154     my $branches = Koha::Libraries->search({}, { order_by => ['branchname'] })->unblessed;
155     my @branches_option;
156     push @branches_option, { value => $_->{branchcode}, lib => $_->{branchname} } for @$branches;
157     unshift @branches_option, { value => "", lib => "" };
158     my @categories_option;
159     push @categories_option, { value => $_->categorycode, lib => $_->description } for @patron_categories;
160     unshift @categories_option, { value => "", lib => "" };
161     my $bsort1 = GetAuthorisedValues("Bsort1");
162     my @sort1_option;
163     push @sort1_option, { value => $_->{authorised_value}, lib => $_->{lib} } for @$bsort1;
164     unshift @sort1_option, { value => "", lib => "" }
165         if @sort1_option;
166     my $bsort2 = GetAuthorisedValues("Bsort2");
167     my @sort2_option;
168     push @sort2_option, { value => $_->{authorised_value}, lib => $_->{lib} } for @$bsort2;
169     unshift @sort2_option, { value => "", lib => "" }
170         if @sort2_option;
171
172     my @mandatoryFields = split( /\|/, C4::Context->preference("BorrowerMandatoryField") );
173
174     my @fields = (
175         {
176             name => "surname",
177             type => "text",
178             mandatory => ( grep /surname/, @mandatoryFields ) ? 1 : 0
179         }
180         ,
181         {
182             name => "firstname",
183             type => "text",
184             mandatory => ( grep /firstname/, @mandatoryFields ) ? 1 : 0,
185         }
186         ,
187         {
188             name => "branchcode",
189             type => "select",
190             option => \@branches_option,
191             mandatory => ( grep /branchcode/, @mandatoryFields ) ? 1 : 0,
192         }
193         ,
194         {
195             name => "categorycode",
196             type => "select",
197             option => \@categories_option,
198             mandatory => ( grep /categorycode/, @mandatoryFields ) ? 1 : 0,
199         }
200         ,
201         {
202             name => "streetnumber",
203             type => "text",
204             mandatory => ( grep /streetnumber/, @mandatoryFields ) ? 1 : 0,
205         }
206         ,
207         {
208             name => "address",
209             type => "text",
210             mandatory => ( grep /address/, @mandatoryFields ) ? 1 : 0,
211         }
212         ,
213         {
214             name => "address2",
215             type => "text",
216             mandatory => ( grep /address2/, @mandatoryFields ) ? 1 : 0,
217         }
218         ,
219         {
220             name => "city",
221             type => "text",
222             mandatory => ( grep /city/, @mandatoryFields ) ? 1 : 0,
223         }
224         ,
225         {
226             name => "state",
227             type => "text",
228             mandatory => ( grep /state/, @mandatoryFields ) ? 1 : 0,
229         }
230         ,
231         {
232             name => "zipcode",
233             type => "text",
234             mandatory => ( grep /zipcode/, @mandatoryFields ) ? 1 : 0,
235         }
236         ,
237         {
238             name => "country",
239             type => "text",
240             mandatory => ( grep /country/, @mandatoryFields ) ? 1 : 0,
241         }
242         ,
243         {
244             name => "email",
245             type => "text",
246             mandatory => ( grep /email/, @mandatoryFields ) ? 1 : 0,
247         }
248         ,
249         {
250             name => "phone",
251             type => "text",
252             mandatory => ( grep /phone/, @mandatoryFields ) ? 1 : 0,
253         }
254         ,
255         {
256             name => "mobile",
257             type => "text",
258             mandatory => ( grep /mobile/, @mandatoryFields ) ? 1 : 0,
259         }
260         ,
261         {
262             name => "sort1",
263             type => @sort1_option ? "select" : "text",
264             option => \@sort1_option,
265             mandatory => ( grep /sort1/, @mandatoryFields ) ? 1 : 0,
266         }
267         ,
268         {
269             name => "sort2",
270             type => @sort2_option ? "select" : "text",
271             option => \@sort2_option,
272             mandatory => ( grep /sort2/, @mandatoryFields ) ? 1 : 0,
273         }
274         ,
275         {
276             name => "dateenrolled",
277             type => "date",
278             mandatory => ( grep /dateenrolled/, @mandatoryFields ) ? 1 : 0,
279         }
280         ,
281         {
282             name => "dateexpiry",
283             type => "date",
284             mandatory => ( grep /dateexpiry/, @mandatoryFields ) ? 1 : 0,
285         }
286         ,
287         {
288             name => "borrowernotes",
289             type => "text",
290             mandatory => ( grep /borrowernotes/, @mandatoryFields ) ? 1 : 0,
291         }
292         ,
293         {
294             name => "opacnote",
295             type => "text",
296             mandatory => ( grep /opacnote/, @mandatoryFields ) ? 1 : 0,
297         }
298         ,
299         {
300             name => "debarred",
301             type => "date",
302             mandatory => ( grep /debarred/, @mandatoryFields ) ? 1 : 0,
303         }
304         ,
305         {
306             name => "debarredcomment",
307             type => "text",
308             mandatory => ( grep /debarredcomment/, @mandatoryFields ) ? 1 : 0,
309         },
310     );
311
312     $template->param('patron_attributes_codes', \@patron_attributes_codes);
313     $template->param('patron_attributes_values', \@patron_attributes_values);
314
315     $template->param( fields => \@fields );
316 }
317
318 # Process modifications
319 if ( $op eq 'do' ) {
320
321     my @disabled = $input->multi_param('disable_input');
322     my $infos;
323     for my $field ( qw/surname firstname branchcode categorycode streetnumber address address2 city state zipcode country email phone mobile sort1 sort2 dateenrolled dateexpiry borrowernotes opacnote debarred debarredcomment/ ) {
324         my $value = $input->param($field);
325         $infos->{$field} = $value if $value;
326         $infos->{$field} = "" if grep { $_ eq $field } @disabled;
327     }
328
329     for my $field ( qw( dateenrolled dateexpiry debarred ) ) {
330         $infos->{$field} = dt_from_string($infos->{$field}) if $infos->{$field};
331     }
332
333     my @attributes = $input->multi_param('patron_attributes');
334     my @attr_values = $input->multi_param('patron_attributes_value');
335
336     my @errors;
337     my @borrowernumbers = $input->multi_param('borrowernumber');
338     # For each borrower selected
339     for my $borrowernumber ( @borrowernumbers ) {
340         # If at least one field are filled, we want to modify the borrower
341         if ( defined $infos ) {
342             # If a debarred date or debarred comment has been submitted make a new debarment
343             if ( $infos->{debarred} || $infos->{debarredcomment} ) {
344                 AddDebarment(
345                     {
346                         borrowernumber => $borrowernumber,
347                         type           => 'MANUAL',
348                         comment        => $infos->{debarredcomment},
349                         expiration     => $infos->{debarred},
350                     });
351             }
352
353             # If debarment date or debarment comment are disabled then remove all debarrments
354             if ( grep { /debarred/ } @disabled ) {
355                 eval {
356                    my $debarrments = GetDebarments( { borrowernumber => $borrowernumber } );
357                    foreach my $debarment (@$debarrments) {
358                       DelDebarment( $debarment->{'borrower_debarment_id'} );
359                    }
360                 };
361             }
362
363             $infos->{borrowernumber} = $borrowernumber;
364             eval { Koha::Patrons->find( $borrowernumber )->set($infos)->store; };
365             if ( $@ ) { # FIXME We could provide better error handling here
366                 my $patron = Koha::Patrons->find( $borrowernumber );
367                 $infos->{cardnumber} = $patron ? $patron->cardnumber || '' : '';
368                 push @errors, { error => "can_not_update", borrowernumber => $infos->{borrowernumber}, cardnumber => $infos->{cardnumber} };
369             }
370         }
371
372         my $patron = Koha::Patrons->find( $borrowernumber );
373         my $i=0;
374         for ( @attributes ) {
375             next unless $_;
376             my $attribute;
377             $attribute->{code} = $_;
378             $attribute->{attribute} = $attr_values[$i];
379             my $attr_type = Koha::Patron::Attribute::Types->find($_);
380             # If this borrower is not in the category of this attribute, we don't want to modify this attribute
381             ++$i and next if $attr_type->category_code and $attr_type->category_code ne $patron->categorycode;
382             my $valuename = "attr" . $i . "_value";
383             if ( grep { $_ eq $valuename } @disabled ) {
384                 # The attribute is disabled, we remove it for this borrower !
385                 eval {
386                     $patron->get_extended_attribute($attribute->{code})->delete;
387                 };
388                 push @errors, { error => $@ } if $@;
389             } else {
390                 eval {
391                     # Note:
392                     # We should not need to filter by branch, but stay on the safe side
393                     # Repeatable are not supported so we can do that - TODO
394                     $patron->extended_attributes->search({'me.code' => $attribute->{code}})->filter_by_branch_limitations->delete;
395                     $patron->add_extended_attribute($attribute);
396                 };
397                 push @errors, { error => $@ } if $@;
398             }
399             $i++;
400         }
401     }
402     $op = "show_results"; # We have process modifications, the user want to view its
403
404     # Construct the results list
405     my @borrowers;
406     my $max_nb_attr = 0;
407     for my $borrowernumber ( @borrowernumbers ) {
408         my $patron = Koha::Patrons->find( $borrowernumber );
409         if ( $patron ) {
410             my $category_description = $patron->category->description;
411             my $borrower = $patron->unblessed;
412             $borrower->{category_description} = $category_description;
413             my $attributes = $patron->extended_attributes;
414             $borrower->{patron_attributes} = $attributes->as_list;
415             $max_nb_attr = $attributes->count if $attributes->count > $max_nb_attr;
416             push @borrowers, $borrower;
417         }
418     }
419     my @patron_attributes_option;
420     for my $borrower ( @borrowers ) {
421         push @patron_attributes_option, { value => "$_->{code}", lib => $_->{code} } for @{ $borrower->{patron_attributes} };
422         my $length = scalar( @{ $borrower->{patron_attributes} } );
423         push @{ $borrower->{patron_attributes} }, {} for ( $length .. $max_nb_attr - 1);
424     }
425
426     my @attributes_header = ();
427     for ( 1 .. scalar( $max_nb_attr ) ) {
428         push @attributes_header, { attribute => "Attributes $_" };
429     }
430
431     $template->param( borrowers => \@borrowers );
432     $template->param( attributes_header => \@attributes_header );
433
434     $template->param( errors => \@errors );
435 } else {
436
437     $template->param( patron_lists => [ GetPatronLists() ] );
438 }
439
440 $template->param(
441     op => $op,
442 );
443 output_html_with_http_headers $input, $cookie, $template->output;
444 exit;