Bug 18555: Create patron list from patron import
[koha.git] / tools / import_borrowers.pl
1 #!/usr/bin/perl
2
3 # Copyright 2007 Liblime
4 # Parts copyright 2010 BibLibre
5 #
6 # This file is part of Koha.
7 #
8 # Koha is free software; you can redistribute it and/or modify it
9 # under the terms of the GNU General Public License as published by
10 # the Free Software Foundation; either version 3 of the License, or
11 # (at your option) any later version.
12 #
13 # Koha is distributed in the hope that it will be useful, but
14 # WITHOUT ANY WARRANTY; without even the implied warranty of
15 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 # GNU General Public License for more details.
17 #
18 # You should have received a copy of the GNU General Public License
19 # along with Koha; if not, see <http://www.gnu.org/licenses>.
20
21 # Script to take some borrowers data in a known format and load it into Koha
22 #
23 # File format
24 #
25 # cardnumber,surname,firstname,title,othernames,initials,streetnumber,streettype,
26 # address line , address line 2, city, zipcode, contry, email, phone, mobile, fax, work email, work phone,
27 # alternate streetnumber, alternate streettype, alternate address line 1, alternate city,
28 # alternate zipcode, alternate country, alternate email, alternate phone, date of birth, branchcode,
29 # categorycode, enrollment date, expiry date, noaddress, lost, debarred, contact surname,
30 # contact firstname, contact title, borrower notes, contact relationship
31 # gender, username, opac note, contact note, password, sort one, sort two
32 #
33 # any fields except cardnumber can be blank but the number of fields must match
34 # dates should be in the format you have set up Koha to expect
35 # branchcode and categorycode need to be valid
36
37 use strict;
38 use warnings;
39
40 use C4::Auth;
41 use C4::Output;
42 use C4::Context;
43 use C4::Members;
44 use C4::Members::Attributes qw(:all);
45 use C4::Members::AttributeTypes;
46 use C4::Members::Messaging;
47 use C4::Reports::Guided;
48 use C4::Templates;
49 use Koha::Patron::Debarments;
50 use Koha::Patrons;
51 use Koha::DateUtils;
52 use Koha::Token;
53 use Koha::Libraries;
54 use Koha::Patron::Categories;
55 use Koha::List::Patron;
56
57 use Text::CSV;
58 # Text::CSV::Unicode, even in binary mode, fails to parse lines with these diacriticals:
59 # ė
60 # č
61
62 use CGI qw ( -utf8 );
63
64 my (@errors, @feedback);
65 my $extended = C4::Context->preference('ExtendedPatronAttributes');
66 my $set_messaging_prefs = C4::Context->preference('EnhancedMessagingPreferences');
67 my @columnkeys = Koha::Patrons->columns();
68 @columnkeys = map { $_ ne 'borrowernumber' ? $_ : () } @columnkeys;
69 if ($extended) {
70     push @columnkeys, 'patron_attributes';
71 }
72
73 my $input = CGI->new();
74 our $csv  = Text::CSV->new({binary => 1});  # binary needed for non-ASCII Unicode
75 #push @feedback, {feedback=>1, name=>'backend', value=>$csv->backend, backend=>$csv->backend}; #XXX
76
77 my ( $template, $loggedinuser, $cookie ) = get_template_and_user({
78         template_name   => "tools/import_borrowers.tt",
79         query           => $input,
80         type            => "intranet",
81         authnotrequired => 0,
82         flagsrequired   => { tools => 'import_patrons' },
83         debug           => 1,
84 });
85
86 # get the patron categories and pass them to the template
87 my @patron_categories = Koha::Patron::Categories->search_limited({}, {order_by => ['description']});
88 $template->param( categories => \@patron_categories );
89 my $columns = C4::Templates::GetColumnDefs( $input )->{borrowers};
90 $columns = [ grep { $_->{field} ne 'borrowernumber' ? $_ : () } @$columns ];
91 $template->param( borrower_fields => $columns );
92
93 if ($input->param('sample')) {
94     print $input->header(
95         -type       => 'application/vnd.sun.xml.calc', # 'application/vnd.ms-excel' ?
96         -attachment => 'patron_import.csv',
97     );
98     $csv->combine(@columnkeys);
99     print $csv->string, "\n";
100     exit 0;
101 }
102 my $uploadborrowers = $input->param('uploadborrowers');
103 my $matchpoint      = $input->param('matchpoint');
104 if ($matchpoint) {
105     $matchpoint =~ s/^patron_attribute_//;
106 }
107 my $overwrite_cardnumber = $input->param('overwrite_cardnumber');
108
109 #create a patronlist
110 my $createpatronlist = $input->param('createpatronlist') || 0;
111 my $dt = dt_from_string();
112 my $timestamp = $dt->ymd('-').' '.$dt->hms(':');
113 my $patronlistname = $uploadborrowers . ' (' . $timestamp .')';
114
115 $template->param( SCRIPT_NAME => '/cgi-bin/koha/tools/import_borrowers.pl' );
116
117 if ( $uploadborrowers && length($uploadborrowers) > 0 ) {
118     die "Wrong CSRF token"
119         unless Koha::Token->new->check_csrf({
120             session_id => scalar $input->cookie('CGISESSID'),
121             token  => scalar $input->param('csrf_token'),
122         });
123
124     #create a patronlist
125     my $createpatronlist = $input->param('createpatronlist');
126     my $dt = dt_from_string();
127     my $timestamp = $dt->ymd('-').' '.$dt->hms(':');
128     my $patronlistname = $uploadborrowers. ' (' . $timestamp .')';
129
130     push @feedback, {feedback=>1, name=>'filename', value=>$uploadborrowers, filename=>$uploadborrowers};
131     my $handle = $input->upload('uploadborrowers');
132     my $uploadinfo = $input->uploadInfo($uploadborrowers);
133     foreach (keys %$uploadinfo) {
134         push @feedback, {feedback=>1, name=>$_, value=>$uploadinfo->{$_}, $_=>$uploadinfo->{$_}};
135     }
136
137     my $imported    = 0;
138     my @imported_borrowers;
139     my $alreadyindb = 0;
140     my $overwritten = 0;
141     my $invalid     = 0;
142     my $matchpoint_attr_type; 
143     my %defaults = $input->Vars;
144
145     # use header line to construct key to column map
146     my $borrowerline = <$handle>;
147     my $status = $csv->parse($borrowerline);
148     ($status) or push @errors, {badheader=>1,line=>$., lineraw=>$borrowerline};
149     my @csvcolumns = $csv->fields();
150     my %csvkeycol;
151     my $col = 0;
152     foreach my $keycol (@csvcolumns) {
153         # columnkeys don't contain whitespace, but some stupid tools add it
154         $keycol =~ s/ +//g;
155         $csvkeycol{$keycol} = $col++;
156     }
157     #warn($borrowerline);
158     my $ext_preserve = $input->param('ext_preserve') || 0;
159     if ($extended) {
160         $matchpoint_attr_type = C4::Members::AttributeTypes->fetch($matchpoint);
161     }
162
163     push @feedback, {feedback=>1, name=>'headerrow', value=>join(', ', @csvcolumns)};
164     my $today = output_pref;
165     my @criticals = qw(surname branchcode categorycode);    # there probably should be others
166     my @bad_dates;  # I've had a few.
167     LINE: while ( my $borrowerline = <$handle> ) {
168         my %borrower;
169         my @missing_criticals;
170         my $patron_attributes;
171         my $status  = $csv->parse($borrowerline);
172         my @columns = $csv->fields();
173         if (! $status) {
174             push @missing_criticals, {badparse=>1, line=>$., lineraw=>$borrowerline};
175         } elsif (@columns == @columnkeys) {
176             @borrower{@columnkeys} = @columns;
177             # MJR: try to fill blanks gracefully by using default values
178             foreach my $key (@columnkeys) {
179                 if ($borrower{$key} !~ /\S/) {
180                     $borrower{$key} = $defaults{$key};
181                 }
182             } 
183         } else {
184             # MJR: try to recover gracefully by using default values
185             foreach my $key (@columnkeys) {
186                 if (defined($csvkeycol{$key}) and $columns[$csvkeycol{$key}] =~ /\S/) { 
187                     $borrower{$key} = $columns[$csvkeycol{$key}];
188                 } elsif ( $defaults{$key} ) {
189                     $borrower{$key} = $defaults{$key};
190                 } elsif ( scalar grep {$key eq $_} @criticals ) {
191                     # a critical field is undefined
192                     push @missing_criticals, {key=>$key, line=>$., lineraw=>$borrowerline};
193                 } else {
194                         $borrower{$key} = '';
195                 }
196             }
197         }
198         #warn join(':',%borrower);
199         if ($borrower{categorycode}) {
200             push @missing_criticals, {key=>'categorycode', line=>$. , lineraw=>$borrowerline, value=>$borrower{categorycode}, category_map=>1}
201                 unless Koha::Patron::Categories->find($borrower{categorycode});
202         } else {
203             push @missing_criticals, {key=>'categorycode', line=>$. , lineraw=>$borrowerline};
204         }
205         if ($borrower{branchcode}) {
206             push @missing_criticals, {key=>'branchcode', line=>$. , lineraw=>$borrowerline, value=>$borrower{branchcode}, branch_map=>1}
207                 unless Koha::Libraries->find($borrower{branchcode});
208         } else {
209             push @missing_criticals, {key=>'branchcode', line=>$. , lineraw=>$borrowerline};
210         }
211         if (@missing_criticals) {
212             foreach (@missing_criticals) {
213                 $_->{borrowernumber} = $borrower{borrowernumber} || 'UNDEF';
214                 $_->{surname}        = $borrower{surname} || 'UNDEF';
215             }
216             $invalid++;
217             (25 > scalar @errors) and push @errors, {missing_criticals=>\@missing_criticals};
218             # The first 25 errors are enough.  Keeping track of 30,000+ would destroy performance.
219             next LINE;
220         }
221         if ($extended) {
222             my $attr_str = $borrower{patron_attributes};
223             $attr_str =~ s/\xe2\x80\x9c/"/g; # fixup double quotes in case we are passed smart quotes
224             $attr_str =~ s/\xe2\x80\x9d/"/g;
225             push @feedback, {feedback=>1, name=>'attribute string', value=>$attr_str, filename=>$uploadborrowers};
226             delete $borrower{patron_attributes};    # not really a field in borrowers, so we don't want to pass it to ModMember.
227             $patron_attributes = extended_attributes_code_value_arrayref($attr_str); 
228         }
229         # Popular spreadsheet applications make it difficult to force date outputs to be zero-padded, but we require it.
230         foreach (qw(dateofbirth dateenrolled dateexpiry)) {
231             my $tempdate = $borrower{$_} or next;
232             $tempdate = eval { output_pref( { dt => dt_from_string( $tempdate ), dateonly => 1, dateformat => 'iso' } ); };
233             if ($tempdate) {
234                 $borrower{$_} = $tempdate;
235             } else {
236                 $borrower{$_} = '';
237                 push @missing_criticals, {key=>$_, line=>$. , lineraw=>$borrowerline, bad_date=>1};
238             }
239         }
240         $borrower{dateenrolled} ||= $today;
241         $borrower{dateexpiry}   ||= Koha::Patron::Categories->find( $borrower{categorycode} )->get_expiry_date( $borrower{dateenrolled} );
242         my $borrowernumber;
243         my $member;
244         if ( ($matchpoint eq 'cardnumber') && ($borrower{'cardnumber'}) ) {
245             $member = Koha::Patrons->find( { cardnumber => $borrower{'cardnumber'} } );
246         } elsif ( ($matchpoint eq 'userid') && ($borrower{'userid'}) ) {
247             $member = Koha::Patrons->find( { userid => $borrower{'userid'} } )->unblessed;
248         } elsif ($extended) {
249             if (defined($matchpoint_attr_type)) {
250                 foreach my $attr (@$patron_attributes) {
251                     if ($attr->{code} eq $matchpoint and $attr->{value} ne '') {
252                         my @borrowernumbers = $matchpoint_attr_type->get_patrons($attr->{value});
253                         $borrowernumber = $borrowernumbers[0] if scalar(@borrowernumbers) == 1;
254                         last;
255                     }
256                 }
257             }
258         }
259
260         if ($member) {
261             $member = $member->unblessed;
262             $borrowernumber = $member->{'borrowernumber'};
263         } else {
264             $member = {};
265         }
266
267         if ( C4::Members::checkcardnumber( $borrower{cardnumber}, $borrowernumber ) ) {
268             push @errors, {
269                 invalid_cardnumber => 1,
270                 borrowernumber => $borrowernumber,
271                 cardnumber => $borrower{cardnumber}
272             };
273             $invalid++;
274             next;
275         }
276
277         if ($borrowernumber) {
278             # borrower exists
279             unless ($overwrite_cardnumber) {
280                 $alreadyindb++;
281                 $template->param('lastalreadyindb'=>$borrower{'surname'}.' / '.$borrowernumber);
282                 next LINE;
283             }
284             $borrower{'borrowernumber'} = $borrowernumber;
285             for my $col (keys %borrower) {
286                 # use values from extant patron unless our csv file includes this column or we provided a default.
287                 # FIXME : You cannot update a field with a  perl-evaluated false value using the defaults.
288
289                 # The password is always encrypted, skip it!
290                 next if $col eq 'password';
291
292                 unless(exists($csvkeycol{$col}) || $defaults{$col}) {
293                     $borrower{$col} = $member->{$col} if($member->{$col}) ;
294                 }
295             }
296
297             # Check if the userid provided does not exist yet
298             if (  exists $borrower{userid}
299                      and $borrower{userid}
300                  and not Check_Userid( $borrower{userid}, $borrower{borrowernumber} ) ) {
301                 push @errors, { duplicate_userid => 1, userid => $borrower{userid} };
302                 $invalid++;
303                 next LINE;
304             }
305
306             unless (ModMember(%borrower)) {
307                 $invalid++;
308                 # until we have better error trapping, we have no way of knowing why ModMember errored out...
309                 push @errors, {unknown_error => 1};
310                 $template->param('lastinvalid'=>$borrower{'surname'}.' / '.$borrowernumber);
311                 next LINE;
312             }
313
314             # Don't add a new restriction if the existing 'combined' restriction matches this one
315             if ( $borrower{debarred} && ( ( $borrower{debarred} ne $member->{debarred} ) || ( $borrower{debarredcomment} ne $member->{debarredcomment} ) ) ) {
316                 # Check to see if this debarment already exists
317                 my $debarrments = GetDebarments(
318                     {
319                         borrowernumber => $borrowernumber,
320                         expiration     => $borrower{debarred},
321                         comment        => $borrower{debarredcomment}
322                     }
323                 );
324                 # If it doesn't, then add it!
325                 unless (@$debarrments) {
326                     AddDebarment(
327                         {
328                             borrowernumber => $borrowernumber,
329                             expiration     => $borrower{debarred},
330                             comment        => $borrower{debarredcomment}
331                         }
332                     );
333                 }
334             }
335
336             if ($extended) {
337                 if ($ext_preserve) {
338                     my $old_attributes = GetBorrowerAttributes($borrowernumber);
339                     $patron_attributes = extended_attributes_merge($old_attributes, $patron_attributes);  #TODO: expose repeatable options in template
340                 }
341                 push @errors, {unknown_error => 1} unless SetBorrowerAttributes($borrower{'borrowernumber'}, $patron_attributes, 'no_branch_limit' );
342             }
343             $overwritten++;
344             $template->param('lastoverwritten'=>$borrower{'surname'}.' / '.$borrowernumber);
345         } else {
346             # FIXME: fixup_cardnumber says to lock table, but the web interface doesn't so this doesn't either.
347             # At least this is closer to AddMember than in members/memberentry.pl
348             if (!$borrower{'cardnumber'}) {
349                 $borrower{'cardnumber'} = fixup_cardnumber(undef);
350             }
351             if ($borrowernumber = AddMember(%borrower)) {
352
353                 if ( $borrower{debarred} ) {
354                     AddDebarment(
355                         {
356                             borrowernumber => $borrowernumber,
357                             expiration     => $borrower{debarred},
358                             comment        => $borrower{debarredcomment}
359                         }
360                     );
361                 }
362
363                 if ($extended) {
364                     SetBorrowerAttributes($borrowernumber, $patron_attributes);
365                 }
366
367                 if ($set_messaging_prefs) {
368                     C4::Members::Messaging::SetMessagingPreferencesFromDefaults({ borrowernumber => $borrowernumber,
369                                                                                   categorycode => $borrower{categorycode} });
370                 }
371
372                 $imported++;
373                 $template->param('lastimported'=>$borrower{'surname'}.' / '.$borrowernumber);
374                 push @imported_borrowers, $borrowernumber; #for patronlist
375             } else {
376                 $invalid++;
377                 push @errors, {unknown_error => 1};
378                 $template->param('lastinvalid'=>$borrower{'surname'}.' / AddMember');
379             }
380         }
381     }
382
383     if ( $imported && $createpatronlist ) {
384         my $patronlist = AddPatronList({ name => $patronlistname });
385         AddPatronsToList({ list => $patronlist, borrowernumbers => \@imported_borrowers });
386         $template->param('patronlistname' => $patronlistname);
387     }
388
389     (@errors  ) and $template->param(  ERRORS=>\@errors  );
390     (@feedback) and $template->param(FEEDBACK=>\@feedback);
391     $template->param(
392         'uploadborrowers' => 1,
393         'imported'        => $imported,
394         'overwritten'     => $overwritten,
395         'alreadyindb'     => $alreadyindb,
396         'invalid'         => $invalid,
397         'total'           => $imported + $alreadyindb + $invalid + $overwritten,
398     );
399
400 } else {
401     if ($extended) {
402         my @matchpoints = ();
403         my @attr_types = C4::Members::AttributeTypes::GetAttributeTypes(undef, 1);
404         foreach my $type (@attr_types) {
405             my $attr_type = C4::Members::AttributeTypes->fetch($type->{code});
406             if ($attr_type->unique_id()) {
407             push @matchpoints, { code =>  "patron_attribute_" . $attr_type->code(), description => $attr_type->description() };
408             }
409         }
410         $template->param(matchpoints => \@matchpoints);
411     }
412
413     $template->param(
414         csrf_token => Koha::Token->new->generate_csrf(
415             { session_id => scalar $input->cookie('CGISESSID'), }
416         ),
417     );
418
419 }
420
421 output_html_with_http_headers $input, $cookie, $template->output;
422