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