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