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