Bug 12929: Restore behavior before bug 12716
[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 under the
9 # terms of the GNU General Public License as published by the Free Software
10 # Foundation; either version 2 of the License, or (at your option) any later
11 # version.
12 #
13 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
14 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
15 # A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
16 #
17 # You should have received a copy of the GNU General Public License along
18 # with Koha; if not, write to the Free Software Foundation, Inc.,
19 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
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, ethnicity, ethnicity notes
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::Dates qw(format_date_in_iso);
43 use C4::Context;
44 use C4::Branch qw/GetBranchesLoop GetBranchName/;
45 use C4::Members;
46 use C4::Members::Attributes qw(:all);
47 use C4::Members::AttributeTypes;
48 use C4::Members::Messaging;
49 use C4::Reports::Guided;
50 use C4::Templates;
51 use Koha::Borrower::Debarments;
52
53 use Text::CSV;
54 # Text::CSV::Unicode, even in binary mode, fails to parse lines with these diacriticals:
55 # ė
56 # č
57
58 use CGI;
59 # use encoding 'utf8';    # don't do this
60
61 my (@errors, @feedback);
62 my $extended = C4::Context->preference('ExtendedPatronAttributes');
63 my $set_messaging_prefs = C4::Context->preference('EnhancedMessagingPreferences');
64 my @columnkeys = C4::Members::columns();
65 if ($extended) {
66     push @columnkeys, 'patron_attributes';
67 }
68
69 my $input = CGI->new();
70 our $csv  = Text::CSV->new({binary => 1});  # binary needed for non-ASCII Unicode
71 #push @feedback, {feedback=>1, name=>'backend', value=>$csv->backend, backend=>$csv->backend}; #XXX
72
73 my ( $template, $loggedinuser, $cookie ) = get_template_and_user({
74         template_name   => "tools/import_borrowers.tt",
75         query           => $input,
76         type            => "intranet",
77         authnotrequired => 0,
78         flagsrequired   => { tools => 'import_patrons' },
79         debug           => 1,
80 });
81
82 # get the branches and pass them to the template
83 my $branches = GetBranchesLoop();
84 $template->param( branches => $branches ) if ( $branches );
85 # get the patron categories and pass them to the template
86 my $categories = GetBorrowercategoryList();
87 $template->param( categories => $categories ) if ( $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 1;
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 $template->param( SCRIPT_NAME => $ENV{'SCRIPT_NAME'} );
109
110 if ( $uploadborrowers && length($uploadborrowers) > 0 ) {
111     push @feedback, {feedback=>1, name=>'filename', value=>$uploadborrowers, filename=>$uploadborrowers};
112     my $handle = $input->upload('uploadborrowers');
113     my $uploadinfo = $input->uploadInfo($uploadborrowers);
114     foreach (keys %$uploadinfo) {
115         push @feedback, {feedback=>1, name=>$_, value=>$uploadinfo->{$_}, $_=>$uploadinfo->{$_}};
116     }
117     my $imported    = 0;
118     my $alreadyindb = 0;
119     my $overwritten = 0;
120     my $invalid     = 0;
121     my $matchpoint_attr_type; 
122     my %defaults = $input->Vars;
123
124     # use header line to construct key to column map
125     my $borrowerline = <$handle>;
126     my $status = $csv->parse($borrowerline);
127     ($status) or push @errors, {badheader=>1,line=>$., lineraw=>$borrowerline};
128     my @csvcolumns = $csv->fields();
129     my %csvkeycol;
130     my $col = 0;
131     foreach my $keycol (@csvcolumns) {
132         # columnkeys don't contain whitespace, but some stupid tools add it
133         $keycol =~ s/ +//g;
134         $csvkeycol{$keycol} = $col++;
135     }
136     #warn($borrowerline);
137     my $ext_preserve = $input->param('ext_preserve') || 0;
138     if ($extended) {
139         $matchpoint_attr_type = C4::Members::AttributeTypes->fetch($matchpoint);
140     }
141
142     push @feedback, {feedback=>1, name=>'headerrow', value=>join(', ', @csvcolumns)};
143     my $today_iso = C4::Dates->new()->output('iso');
144     my @criticals = qw(surname branchcode categorycode);    # there probably should be others
145     my @bad_dates;  # I've had a few.
146     my $date_re = C4::Dates->new->regexp('syspref');
147     my  $iso_re = C4::Dates->new->regexp('iso');
148     LINE: while ( my $borrowerline = <$handle> ) {
149         my %borrower;
150         my @missing_criticals;
151         my $patron_attributes;
152         my $status  = $csv->parse($borrowerline);
153         my @columns = $csv->fields();
154         if (! $status) {
155             push @missing_criticals, {badparse=>1, line=>$., lineraw=>$borrowerline};
156         } elsif (@columns == @columnkeys) {
157             @borrower{@columnkeys} = @columns;
158             # MJR: try to fill blanks gracefully by using default values
159             foreach my $key (@columnkeys) {
160                 if ($borrower{$key} !~ /\S/) {
161                     $borrower{$key} = $defaults{$key};
162                 }
163             } 
164         } else {
165             # MJR: try to recover gracefully by using default values
166             foreach my $key (@columnkeys) {
167                 if (defined($csvkeycol{$key}) and $columns[$csvkeycol{$key}] =~ /\S/) { 
168                     $borrower{$key} = $columns[$csvkeycol{$key}];
169                 } elsif ( $defaults{$key} ) {
170                     $borrower{$key} = $defaults{$key};
171                 } elsif ( scalar grep {$key eq $_} @criticals ) {
172                     # a critical field is undefined
173                     push @missing_criticals, {key=>$key, line=>$., lineraw=>$borrowerline};
174                 } else {
175                         $borrower{$key} = '';
176                 }
177             }
178         }
179         #warn join(':',%borrower);
180         if ($borrower{categorycode}) {
181             push @missing_criticals, {key=>'categorycode', line=>$. , lineraw=>$borrowerline, value=>$borrower{categorycode}, category_map=>1}
182                 unless GetBorrowercategory($borrower{categorycode});
183         } else {
184             push @missing_criticals, {key=>'categorycode', line=>$. , lineraw=>$borrowerline};
185         }
186         if ($borrower{branchcode}) {
187             push @missing_criticals, {key=>'branchcode', line=>$. , lineraw=>$borrowerline, value=>$borrower{branchcode}, branch_map=>1}
188                 unless GetBranchName($borrower{branchcode});
189         } else {
190             push @missing_criticals, {key=>'branchcode', line=>$. , lineraw=>$borrowerline};
191         }
192         if (@missing_criticals) {
193             foreach (@missing_criticals) {
194                 $_->{borrowernumber} = $borrower{borrowernumber} || 'UNDEF';
195                 $_->{surname}        = $borrower{surname} || 'UNDEF';
196             }
197             $invalid++;
198             (25 > scalar @errors) and push @errors, {missing_criticals=>\@missing_criticals};
199             # The first 25 errors are enough.  Keeping track of 30,000+ would destroy performance.
200             next LINE;
201         }
202         if ($extended) {
203             my $attr_str = $borrower{patron_attributes};
204             $attr_str =~ s/\xe2\x80\x9c/"/g; # fixup double quotes in case we are passed smart quotes
205             $attr_str =~ s/\xe2\x80\x9d/"/g;
206             push @feedback, {feedback=>1, name=>'attribute string', value=>$attr_str, filename=>$uploadborrowers};
207             delete $borrower{patron_attributes};    # not really a field in borrowers, so we don't want to pass it to ModMember.
208             $patron_attributes = extended_attributes_code_value_arrayref($attr_str); 
209         }
210         # Popular spreadsheet applications make it difficult to force date outputs to be zero-padded, but we require it.
211         foreach (qw(dateofbirth dateenrolled dateexpiry)) {
212             my $tempdate = $borrower{$_} or next;
213             if ($tempdate =~ /$date_re/) {
214                 $borrower{$_} = format_date_in_iso($tempdate);
215             } elsif ($tempdate =~ /$iso_re/) {
216                 $borrower{$_} = $tempdate;
217             } else {
218                 $borrower{$_} = '';
219                 push @missing_criticals, {key=>$_, line=>$. , lineraw=>$borrowerline, bad_date=>1};
220             }
221         }
222         $borrower{dateenrolled} = $today_iso unless $borrower{dateenrolled};
223         $borrower{dateexpiry} = GetExpiryDate($borrower{categorycode},$borrower{dateenrolled}) unless $borrower{dateexpiry}; 
224         my $borrowernumber;
225         my $member;
226         if ( ($matchpoint eq 'cardnumber') && ($borrower{'cardnumber'}) ) {
227             $member = GetMember( 'cardnumber' => $borrower{'cardnumber'} );
228             if ($member) {
229                 $borrowernumber = $member->{'borrowernumber'};
230             }
231         } elsif ($extended) {
232             if (defined($matchpoint_attr_type)) {
233                 foreach my $attr (@$patron_attributes) {
234                     if ($attr->{code} eq $matchpoint and $attr->{value} ne '') {
235                         my @borrowernumbers = $matchpoint_attr_type->get_patrons($attr->{value});
236                         $borrowernumber = $borrowernumbers[0] if scalar(@borrowernumbers) == 1;
237                         last;
238                     }
239                 }
240             }
241         }
242
243         if ( C4::Members::checkcardnumber( $borrower{cardnumber}, $borrowernumber ) ) {
244             push @errors, {
245                 invalid_cardnumber => 1,
246                 borrowernumber => $borrowernumber,
247                 cardnumber => $borrower{cardnumber}
248             };
249             $invalid++;
250             next;
251         }
252
253
254         if ($borrowernumber) {
255             # borrower exists
256             unless ($overwrite_cardnumber) {
257                 $alreadyindb++;
258                 $template->param('lastalreadyindb'=>$borrower{'surname'}.' / '.$borrowernumber);
259                 next LINE;
260             }
261             $borrower{'borrowernumber'} = $borrowernumber;
262             for my $col (keys %borrower) {
263                 # use values from extant patron unless our csv file includes this column or we provided a default.
264                 # FIXME : You cannot update a field with a  perl-evaluated false value using the defaults.
265
266                 # The password is always encrypted, skip it!
267                 next if $col eq 'password';
268
269                 unless(exists($csvkeycol{$col}) || $defaults{$col}) {
270                     $borrower{$col} = $member->{$col} if($member->{$col}) ;
271                 }
272             }
273             unless (ModMember(%borrower)) {
274                 $invalid++;
275                 # untill we have better error trapping, we have no way of knowing why ModMember errored out...
276                 push @errors, {unknown_error => 1};
277                 $template->param('lastinvalid'=>$borrower{'surname'}.' / '.$borrowernumber);
278                 next LINE;
279             }
280             if ( $borrower{debarred} ) {
281                 # Check to see if this debarment already exists
282                 my $debarrments = GetDebarments(
283                     {
284                         borrowernumber => $borrowernumber,
285                         expiration     => $borrower{debarred},
286                         comment        => $borrower{debarredcomment}
287                     }
288                 );
289                 # If it doesn't, then add it!
290                 unless (@$debarrments) {
291                     AddDebarment(
292                         {
293                             borrowernumber => $borrowernumber,
294                             expiration     => $borrower{debarred},
295                             comment        => $borrower{debarredcomment}
296                         }
297                     );
298                 }
299             }
300             if ($extended) {
301                 if ($ext_preserve) {
302                     my $old_attributes = GetBorrowerAttributes($borrowernumber);
303                     $patron_attributes = extended_attributes_merge($old_attributes, $patron_attributes);  #TODO: expose repeatable options in template
304                 }
305                 push @errors, {unknown_error => 1} unless SetBorrowerAttributes($borrower{'borrowernumber'}, $patron_attributes);
306             }
307             $overwritten++;
308             $template->param('lastoverwritten'=>$borrower{'surname'}.' / '.$borrowernumber);
309         } else {
310             # FIXME: fixup_cardnumber says to lock table, but the web interface doesn't so this doesn't either.
311             # At least this is closer to AddMember than in members/memberentry.pl
312             if (!$borrower{'cardnumber'}) {
313                 $borrower{'cardnumber'} = fixup_cardnumber(undef);
314             }
315             if ($borrowernumber = AddMember(%borrower)) {
316
317                 if ( $borrower{debarred} ) {
318                     AddDebarment(
319                         {
320                             borrowernumber => $borrowernumber,
321                             expiration     => $borrower{debarred},
322                             comment        => $borrower{debarredcomment}
323                         }
324                     );
325                 }
326
327                 if ($extended) {
328                     SetBorrowerAttributes($borrowernumber, $patron_attributes);
329                 }
330
331                 if ($set_messaging_prefs) {
332                     C4::Members::Messaging::SetMessagingPreferencesFromDefaults({ borrowernumber => $borrowernumber,
333                                                                                   categorycode => $borrower{categorycode} });
334                 }
335
336                 $imported++;
337                 $template->param('lastimported'=>$borrower{'surname'}.' / '.$borrowernumber);
338             } else {
339                 $invalid++;
340                 push @errors, {unknown_error => 1};
341                 $template->param('lastinvalid'=>$borrower{'surname'}.' / AddMember');
342             }
343         }
344     }
345     (@errors  ) and $template->param(  ERRORS=>\@errors  );
346     (@feedback) and $template->param(FEEDBACK=>\@feedback);
347     $template->param(
348         'uploadborrowers' => 1,
349         'imported'        => $imported,
350         'overwritten'     => $overwritten,
351         'alreadyindb'     => $alreadyindb,
352         'invalid'         => $invalid,
353         'total'           => $imported + $alreadyindb + $invalid + $overwritten,
354     );
355
356 } else {
357     if ($extended) {
358         my @matchpoints = ();
359         my @attr_types = C4::Members::AttributeTypes::GetAttributeTypes(undef, 1);
360         foreach my $type (@attr_types) {
361             my $attr_type = C4::Members::AttributeTypes->fetch($type->{code});
362             if ($attr_type->unique_id()) {
363             push @matchpoints, { code =>  "patron_attribute_" . $attr_type->code(), description => $attr_type->description() };
364             }
365         }
366         $template->param(matchpoints => \@matchpoints);
367     }
368 }
369
370 output_html_with_http_headers $input, $cookie, $template->output;
371