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