eaa93eaf8f4525ad111f6b8074d4caaa2ccfe5c2
[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 ) or die "Not logged in";
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                 $patron = $patron->unblessed;
96                 $patron->{patron_attributes} = C4::Members::Attributes::GetBorrowerAttributes( $patron->{borrowernumber} );
97                 $max_nb_attr = scalar( @{ $patron->{patron_attributes} } )
98                     if scalar( @{ $patron->{patron_attributes} } ) > $max_nb_attr;
99                 push @borrowers, $patron;
100             } else {
101                 push @notfoundcardnumbers, $cardnumber;
102             }
103         } else {
104             push @notfoundcardnumbers, $cardnumber;
105         }
106     }
107
108     # Just for a correct display
109     for my $borrower ( @borrowers ) {
110         my $length = scalar( @{ $borrower->{patron_attributes} } );
111         push @{ $borrower->{patron_attributes} }, {} for ( $length .. $max_nb_attr - 1);
112     }
113
114     # Construct the patron attributes list
115     my @patron_attributes_values;
116     my @patron_attributes_codes;
117     my $patron_attribute_types = C4::Members::AttributeTypes::GetAttributeTypes_hashref('all');
118     my @patron_categories = Koha::Patron::Categories->search_limited({}, {order_by => ['description']});
119     for ( values %$patron_attribute_types ) {
120         my $attr_type = C4::Members::AttributeTypes->fetch( $_->{code} );
121         # TODO Repeatable attributes are not correctly managed and can cause data lost.
122         # This should be implemented.
123         next if $attr_type->{repeatable};
124         next if $attr_type->{unique_id}; # Don't display patron attributes that must be unqiue
125         my $options = $attr_type->authorised_value_category
126             ? GetAuthorisedValues( $attr_type->authorised_value_category )
127             : undef;
128         push @patron_attributes_values,
129             {
130                 attribute_code => $_->{code},
131                 options        => $options,
132             };
133
134         my $category_code = $_->{category_code};
135         my ( $category_lib ) = map {
136             ( defined $category_code and $_->categorycode eq $category_code ) ? $_->description : ()
137         } @patron_categories;
138         push @patron_attributes_codes,
139             {
140                 attribute_code => $_->{code},
141                 attribute_lib  => $_->{description},
142                 category_lib   => $category_lib,
143                 type           => $attr_type->authorised_value_category ? 'select' : 'text',
144             };
145     }
146
147     my @attributes_header = ();
148     for ( 1 .. scalar( $max_nb_attr ) ) {
149         push @attributes_header, { attribute => "Attributes $_" };
150     }
151     $template->param( borrowers => \@borrowers );
152     $template->param( attributes_header => \@attributes_header );
153     @notfoundcardnumbers = map { { cardnumber => $_ } } @notfoundcardnumbers;
154     $template->param( notfoundcardnumbers => \@notfoundcardnumbers )
155         if @notfoundcardnumbers;
156
157     # Construct drop-down list values
158     my $branches = Koha::Libraries->search({}, { order_by => ['branchname'] })->unblessed;
159     my @branches_option;
160     push @branches_option, { value => $_->{branchcode}, lib => $_->{branchname} } for @$branches;
161     unshift @branches_option, { value => "", lib => "" };
162     my @categories_option;
163     push @categories_option, { value => $_->categorycode, lib => $_->description } for @patron_categories;
164     unshift @categories_option, { value => "", lib => "" };
165     my $bsort1 = GetAuthorisedValues("Bsort1");
166     my @sort1_option;
167     push @sort1_option, { value => $_->{authorised_value}, lib => $_->{lib} } for @$bsort1;
168     unshift @sort1_option, { value => "", lib => "" }
169         if @sort1_option;
170     my $bsort2 = GetAuthorisedValues("Bsort2");
171     my @sort2_option;
172     push @sort2_option, { value => $_->{authorised_value}, lib => $_->{lib} } for @$bsort2;
173     unshift @sort2_option, { value => "", lib => "" }
174         if @sort2_option;
175
176     my @mandatoryFields = split( /\|/, C4::Context->preference("BorrowerMandatoryField") );
177
178     my @fields = (
179         {
180             name => "surname",
181             type => "text",
182             mandatory => ( grep /surname/, @mandatoryFields ) ? 1 : 0
183         }
184         ,
185         {
186             name => "firstname",
187             type => "text",
188             mandatory => ( grep /firstname/, @mandatoryFields ) ? 1 : 0,
189         }
190         ,
191         {
192             name => "branchcode",
193             type => "select",
194             option => \@branches_option,
195             mandatory => ( grep /branchcode/, @mandatoryFields ) ? 1 : 0,
196         }
197         ,
198         {
199             name => "categorycode",
200             type => "select",
201             option => \@categories_option,
202             mandatory => ( grep /categorycode/, @mandatoryFields ) ? 1 : 0,
203         }
204         ,
205         {
206             name => "city",
207             type => "text",
208             mandatory => ( grep /city/, @mandatoryFields ) ? 1 : 0,
209         }
210         ,
211         {
212             name => "state",
213             type => "text",
214             mandatory => ( grep /state/, @mandatoryFields ) ? 1 : 0,
215         }
216         ,
217         {
218             name => "zipcode",
219             type => "text",
220             mandatory => ( grep /zipcode/, @mandatoryFields ) ? 1 : 0,
221         }
222         ,
223         {
224             name => "country",
225             type => "text",
226             mandatory => ( grep /country/, @mandatoryFields ) ? 1 : 0,
227         }
228         ,
229         {
230             name => "sort1",
231             type => @sort1_option ? "select" : "text",
232             option => \@sort1_option,
233             mandatory => ( grep /sort1/, @mandatoryFields ) ? 1 : 0,
234         }
235         ,
236         {
237             name => "sort2",
238             type => @sort2_option ? "select" : "text",
239             option => \@sort2_option,
240             mandatory => ( grep /sort2/, @mandatoryFields ) ? 1 : 0,
241         }
242         ,
243         {
244             name => "dateenrolled",
245             type => "date",
246             mandatory => ( grep /dateenrolled/, @mandatoryFields ) ? 1 : 0,
247         }
248         ,
249         {
250             name => "dateexpiry",
251             type => "date",
252             mandatory => ( grep /dateexpiry/, @mandatoryFields ) ? 1 : 0,
253         }
254         ,
255         {
256             name => "borrowernotes",
257             type => "text",
258             mandatory => ( grep /borrowernotes/, @mandatoryFields ) ? 1 : 0,
259         }
260         ,
261         {
262             name => "opacnote",
263             type => "text",
264             mandatory => ( grep /opacnote/, @mandatoryFields ) ? 1 : 0,
265         }
266         ,
267         {
268             name => "debarred",
269             type => "date",
270             mandatory => ( grep /debarred/, @mandatoryFields ) ? 1 : 0,
271         }
272         ,
273         {
274             name => "debarredcomment",
275             type => "text",
276             mandatory => ( grep /debarredcomment/, @mandatoryFields ) ? 1 : 0,
277         },
278     );
279
280     $template->param('patron_attributes_codes', \@patron_attributes_codes);
281     $template->param('patron_attributes_values', \@patron_attributes_values);
282
283     $template->param( fields => \@fields );
284 }
285
286 # Process modifications
287 if ( $op eq 'do' ) {
288
289     my @disabled = $input->multi_param('disable_input');
290     my $infos;
291     for my $field ( qw/surname firstname branchcode categorycode city state zipcode country sort1 sort2 dateenrolled dateexpiry borrowernotes opacnote debarred debarredcomment/ ) {
292         my $value = $input->param($field);
293         $infos->{$field} = $value if $value;
294         $infos->{$field} = "" if grep { /^$field$/ } @disabled;
295     }
296
297     for my $field ( qw( dateenrolled dateexpiry debarred ) ) {
298         $infos->{$field} = dt_from_string($infos->{$field}) if $infos->{$field};
299     }
300
301     my @attributes = $input->multi_param('patron_attributes');
302     my @attr_values = $input->multi_param('patron_attributes_value');
303
304     my @errors;
305     my @borrowernumbers = $input->multi_param('borrowernumber');
306     # For each borrower selected
307     for my $borrowernumber ( @borrowernumbers ) {
308         # If at least one field are filled, we want to modify the borrower
309         if ( defined $infos ) {
310             # If a debarred date or debarred comment has been submitted make a new debarment
311             if ( $infos->{debarred} || $infos->{debarredcomment} ) {
312                 AddDebarment(
313                     {
314                         borrowernumber => $borrowernumber,
315                         type           => 'MANUAL',
316                         comment        => $infos->{debarredcomment},
317                         expiration     => $infos->{debarred},
318                     });
319             }
320
321             # If debarment date or debarment comment are disabled then remove all debarrments
322             if ( grep { /debarred/ } @disabled ) {
323                 eval {
324                    my $debarrments = GetDebarments( { borrowernumber => $borrowernumber } );
325                    foreach my $debarment (@$debarrments) {
326                       DelDebarment( $debarment->{'borrower_debarment_id'} );
327                    }
328                 };
329             }
330
331             $infos->{borrowernumber} = $borrowernumber;
332             eval { Koha::Patrons->find( $borrowernumber )->set($infos)->store; };
333             if ( $@ ) { # FIXME We could provide better error handling here
334                 my $patron = Koha::Patrons->find( $borrowernumber );
335                 $infos->{cardnumber} = $patron ? $patron->cardnumber || '' : '';
336                 push @errors, { error => "can_not_update", borrowernumber => $infos->{borrowernumber}, cardnumber => $infos->{cardnumber} };
337             }
338         }
339
340         my $borrower_categorycode = Koha::Patrons->find( $borrowernumber )->categorycode;
341         my $i=0;
342         for ( @attributes ) {
343             next unless $_;
344             my $attribute;
345             $attribute->{code} = $_;
346             $attribute->{attribute} = $attr_values[$i];
347             my $attr_type = C4::Members::AttributeTypes->fetch( $_ );
348             # If this borrower is not in the category of this attribute, we don't want to modify this attribute
349             ++$i and next if $attr_type->{category_code} and $attr_type->{category_code} ne $borrower_categorycode;
350             my $valuename = "attr" . $i . "_value";
351             if ( grep { /^$valuename$/ } @disabled ) {
352                 # The attribute is disabled, we remove it for this borrower !
353                 eval {
354                     C4::Members::Attributes::DeleteBorrowerAttribute( $borrowernumber, $attribute );
355                 };
356                 push @errors, { error => $@ } if $@;
357             } else {
358                 eval {
359                     C4::Members::Attributes::UpdateBorrowerAttribute( $borrowernumber, $attribute );
360                 };
361                 push @errors, { error => $@ } if $@;
362             }
363             $i++;
364         }
365     }
366     $op = "show_results"; # We have process modifications, the user want to view its
367
368     # Construct the results list
369     my @borrowers;
370     my $max_nb_attr = 0;
371     for my $borrowernumber ( @borrowernumbers ) {
372         my $patron = Koha::Patrons->find( $borrowernumber );
373         if ( $patron ) {
374             $patron = $patron->unblessed;
375             $patron->{patron_attributes} = C4::Members::Attributes::GetBorrowerAttributes( $patron->{borrowernumber} );
376             $max_nb_attr = scalar( @{ $patron->{patron_attributes} } )
377                 if scalar( @{ $patron->{patron_attributes} } ) > $max_nb_attr;
378             push @borrowers, $patron;
379         }
380     }
381     my @patron_attributes_option;
382     for my $borrower ( @borrowers ) {
383         push @patron_attributes_option, { value => "$_->{code}", lib => $_->{code} } for @{ $borrower->{patron_attributes} };
384         my $length = scalar( @{ $borrower->{patron_attributes} } );
385         push @{ $borrower->{patron_attributes} }, {} for ( $length .. $max_nb_attr - 1);
386     }
387
388     my @attributes_header = ();
389     for ( 1 .. scalar( $max_nb_attr ) ) {
390         push @attributes_header, { attribute => "Attributes $_" };
391     }
392
393     $template->param( borrowers => \@borrowers );
394     $template->param( attributes_header => \@attributes_header );
395
396     $template->param( errors => \@errors );
397 } else {
398
399     $template->param( patron_lists => [ GetPatronLists() ] );
400 }
401
402 $template->param(
403     op => $op,
404 );
405 output_html_with_http_headers $input, $cookie, $template->output;
406 exit;