Bug 12467 [QA Followup] - Unit Tests
[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
66 my $input = CGI->new();
67 our $csv  = Text::CSV->new({binary => 1});  # binary needed for non-ASCII Unicode
68 #push @feedback, {feedback=>1, name=>'backend', value=>$csv->backend, backend=>$csv->backend}; #XXX
69
70 my ( $template, $loggedinuser, $cookie ) = get_template_and_user({
71         template_name   => "tools/import_borrowers.tt",
72         query           => $input,
73         type            => "intranet",
74         authnotrequired => 0,
75         flagsrequired   => { tools => 'import_patrons' },
76         debug           => 1,
77 });
78
79 # get the branches and pass them to the template
80 my $branches = GetBranchesLoop();
81 $template->param( branches => $branches ) if ( $branches );
82 # get the patron categories and pass them to the template
83 my $categories = GetBorrowercategoryList();
84 $template->param( categories => $categories ) if ( $categories );
85 my $columns = C4::Templates::GetColumnDefs( $input );
86 $template->param( borrower_fields => $columns->{borrowers} );
87
88 if ($input->param('sample')) {
89     print $input->header(
90         -type       => 'application/vnd.sun.xml.calc', # 'application/vnd.ms-excel' ?
91         -attachment => 'patron_import.csv',
92     );
93     $csv->combine(@columnkeys);
94     print $csv->string, "\n";
95     exit 1;
96 }
97 my $uploadborrowers = $input->param('uploadborrowers');
98 my $matchpoint      = $input->param('matchpoint');
99 if ($matchpoint) {
100     $matchpoint =~ s/^patron_attribute_//;
101 }
102 my $overwrite_cardnumber = $input->param('overwrite_cardnumber');
103
104 $template->param( SCRIPT_NAME => $ENV{'SCRIPT_NAME'} );
105
106 if ( $uploadborrowers && length($uploadborrowers) > 0 ) {
107     push @feedback, {feedback=>1, name=>'filename', value=>$uploadborrowers, filename=>$uploadborrowers};
108     my $handle = $input->upload('uploadborrowers');
109     my $uploadinfo = $input->uploadInfo($uploadborrowers);
110     foreach (keys %$uploadinfo) {
111         push @feedback, {feedback=>1, name=>$_, value=>$uploadinfo->{$_}, $_=>$uploadinfo->{$_}};
112     }
113     my $imported    = 0;
114     my $alreadyindb = 0;
115     my $overwritten = 0;
116     my $invalid     = 0;
117     my $matchpoint_attr_type; 
118     my %defaults = $input->Vars;
119
120     # use header line to construct key to column map
121     my $borrowerline = <$handle>;
122     my $status = $csv->parse($borrowerline);
123     ($status) or push @errors, {badheader=>1,line=>$., lineraw=>$borrowerline};
124     my @csvcolumns = $csv->fields();
125     my %csvkeycol;
126     my $col = 0;
127     foreach my $keycol (@csvcolumns) {
128         # columnkeys don't contain whitespace, but some stupid tools add it
129         $keycol =~ s/ +//g;
130         $csvkeycol{$keycol} = $col++;
131     }
132     #warn($borrowerline);
133     my $ext_preserve = $input->param('ext_preserve') || 0;
134     if ($extended) {
135         $matchpoint_attr_type = C4::Members::AttributeTypes->fetch($matchpoint);
136     }
137
138     push @feedback, {feedback=>1, name=>'headerrow', value=>join(', ', @csvcolumns)};
139     my $today_iso = C4::Dates->new()->output('iso');
140     my @criticals = qw(surname branchcode categorycode);    # there probably should be others
141     my @bad_dates;  # I've had a few.
142     my $date_re = C4::Dates->new->regexp('syspref');
143     my  $iso_re = C4::Dates->new->regexp('iso');
144     LINE: while ( my $borrowerline = <$handle> ) {
145         my %borrower;
146         my @missing_criticals;
147         my $patron_attributes;
148         my $status  = $csv->parse($borrowerline);
149         my @columns = $csv->fields();
150         if (! $status) {
151             push @missing_criticals, {badparse=>1, line=>$., lineraw=>$borrowerline};
152         } elsif (@columns == @columnkeys) {
153             @borrower{@columnkeys} = @columns;
154             # MJR: try to fill blanks gracefully by using default values
155             foreach my $key (@columnkeys) {
156                 if ($borrower{$key} !~ /\S/) {
157                     $borrower{$key} = $defaults{$key};
158                 }
159             } 
160         } else {
161             # MJR: try to recover gracefully by using default values
162             foreach my $key (@columnkeys) {
163                 if (defined($csvkeycol{$key}) and $columns[$csvkeycol{$key}] =~ /\S/) { 
164                     $borrower{$key} = $columns[$csvkeycol{$key}];
165                 } elsif ( $defaults{$key} ) {
166                     $borrower{$key} = $defaults{$key};
167                 } elsif ( scalar grep {$key eq $_} @criticals ) {
168                     # a critical field is undefined
169                     push @missing_criticals, {key=>$key, line=>$., lineraw=>$borrowerline};
170                 } else {
171                         $borrower{$key} = '';
172                 }
173             }
174         }
175         #warn join(':',%borrower);
176         if ($borrower{categorycode}) {
177             push @missing_criticals, {key=>'categorycode', line=>$. , lineraw=>$borrowerline, value=>$borrower{categorycode}, category_map=>1}
178                 unless GetBorrowercategory($borrower{categorycode});
179         } else {
180             push @missing_criticals, {key=>'categorycode', line=>$. , lineraw=>$borrowerline};
181         }
182         if ($borrower{branchcode}) {
183             push @missing_criticals, {key=>'branchcode', line=>$. , lineraw=>$borrowerline, value=>$borrower{branchcode}, branch_map=>1}
184                 unless GetBranchName($borrower{branchcode});
185         } else {
186             push @missing_criticals, {key=>'branchcode', line=>$. , lineraw=>$borrowerline};
187         }
188         if (@missing_criticals) {
189             foreach (@missing_criticals) {
190                 $_->{borrowernumber} = $borrower{borrowernumber} || 'UNDEF';
191                 $_->{surname}        = $borrower{surname} || 'UNDEF';
192             }
193             $invalid++;
194             (25 > scalar @errors) and push @errors, {missing_criticals=>\@missing_criticals};
195             # The first 25 errors are enough.  Keeping track of 30,000+ would destroy performance.
196             next LINE;
197         }
198         if ($extended) {
199             my $attr_str = $borrower{patron_attributes};
200             $attr_str =~ s/\xe2\x80\x9c/"/g; # fixup double quotes in case we are passed smart quotes
201             $attr_str =~ s/\xe2\x80\x9d/"/g;
202             push @feedback, {feedback=>1, name=>'attribute string', value=>$attr_str, filename=>$uploadborrowers};
203             delete $borrower{patron_attributes};    # not really a field in borrowers, so we don't want to pass it to ModMember.
204             $patron_attributes = extended_attributes_code_value_arrayref($attr_str); 
205         }
206         # Popular spreadsheet applications make it difficult to force date outputs to be zero-padded, but we require it.
207         foreach (qw(dateofbirth dateenrolled dateexpiry)) {
208             my $tempdate = $borrower{$_} or next;
209             if ($tempdate =~ /$date_re/) {
210                 $borrower{$_} = format_date_in_iso($tempdate);
211             } elsif ($tempdate =~ /$iso_re/) {
212                 $borrower{$_} = $tempdate;
213             } else {
214                 $borrower{$_} = '';
215                 push @missing_criticals, {key=>$_, line=>$. , lineraw=>$borrowerline, bad_date=>1};
216             }
217         }
218         $borrower{dateenrolled} = $today_iso unless $borrower{dateenrolled};
219         $borrower{dateexpiry} = GetExpiryDate($borrower{categorycode},$borrower{dateenrolled}) unless $borrower{dateexpiry}; 
220         my $borrowernumber;
221         my $member;
222         if ( ($matchpoint eq 'cardnumber') && ($borrower{'cardnumber'}) ) {
223             $member = GetMember( 'cardnumber' => $borrower{'cardnumber'} );
224             if ($member) {
225                 $borrowernumber = $member->{'borrowernumber'};
226             }
227         } elsif ($extended) {
228             if (defined($matchpoint_attr_type)) {
229                 foreach my $attr (@$patron_attributes) {
230                     if ($attr->{code} eq $matchpoint and $attr->{value} ne '') {
231                         my @borrowernumbers = $matchpoint_attr_type->get_patrons($attr->{value});
232                         $borrowernumber = $borrowernumbers[0] if scalar(@borrowernumbers) == 1;
233                         last;
234                     }
235                 }
236             }
237         }
238
239         if ( C4::Members::checkcardnumber( $borrower{cardnumber}, $borrowernumber ) ) {
240             push @errors, {
241                 invalid_cardnumber => 1,
242                 borrowernumber => $borrowernumber,
243                 cardnumber => $borrower{cardnumber}
244             };
245             $invalid++;
246             next;
247         }
248
249
250         if ($borrowernumber) {
251             # borrower exists
252             unless ($overwrite_cardnumber) {
253                 $alreadyindb++;
254                 $template->param('lastalreadyindb'=>$borrower{'surname'}.' / '.$borrowernumber);
255                 next LINE;
256             }
257             $borrower{'borrowernumber'} = $borrowernumber;
258             for my $col (keys %borrower) {
259                 # use values from extant patron unless our csv file includes this column or we provided a default.
260                 # FIXME : You cannot update a field with a  perl-evaluated false value using the defaults.
261
262                 # The password is always encrypted, skip it!
263                 next if $col eq 'password';
264
265                 unless(exists($csvkeycol{$col}) || $defaults{$col}) {
266                     $borrower{$col} = $member->{$col} if($member->{$col}) ;
267                 }
268             }
269             unless (ModMember(%borrower)) {
270                 $invalid++;
271                 # untill we have better error trapping, we have no way of knowing why ModMember errored out...
272                 push @errors, {unknown_error => 1};
273                 $template->param('lastinvalid'=>$borrower{'surname'}.' / '.$borrowernumber);
274                 next LINE;
275             }
276             if ( $borrower{debarred} ) {
277                 # Check to see if this debarment already exists
278                 my $debarrments = GetDebarments(
279                     {
280                         borrowernumber => $borrowernumber,
281                         expiration     => $borrower{debarred},
282                         comment        => $borrower{debarredcomment}
283                     }
284                 );
285                 # If it doesn't, then add it!
286                 unless (@$debarrments) {
287                     AddDebarment(
288                         {
289                             borrowernumber => $borrowernumber,
290                             expiration     => $borrower{debarred},
291                             comment        => $borrower{debarredcomment}
292                         }
293                     );
294                 }
295             }
296             if ($extended) {
297                 if ($ext_preserve) {
298                     my $old_attributes = GetBorrowerAttributes($borrowernumber);
299                     $patron_attributes = extended_attributes_merge($old_attributes, $patron_attributes);  #TODO: expose repeatable options in template
300                 }
301                 push @errors, {unknown_error => 1} unless SetBorrowerAttributes($borrower{'borrowernumber'}, $patron_attributes);
302             }
303             $overwritten++;
304             $template->param('lastoverwritten'=>$borrower{'surname'}.' / '.$borrowernumber);
305         } else {
306             # FIXME: fixup_cardnumber says to lock table, but the web interface doesn't so this doesn't either.
307             # At least this is closer to AddMember than in members/memberentry.pl
308             if (!$borrower{'cardnumber'}) {
309                 $borrower{'cardnumber'} = fixup_cardnumber(undef);
310             }
311             if ($borrowernumber = AddMember(%borrower)) {
312
313                 if ( $borrower{debarred} ) {
314                     AddDebarment(
315                         {
316                             borrowernumber => $borrowernumber,
317                             expiration     => $borrower{debarred},
318                             comment        => $borrower{debarredcomment}
319                         }
320                     );
321                 }
322
323                 if ($extended) {
324                     SetBorrowerAttributes($borrowernumber, $patron_attributes);
325                 }
326
327                 if ($set_messaging_prefs) {
328                     C4::Members::Messaging::SetMessagingPreferencesFromDefaults({ borrowernumber => $borrowernumber,
329                                                                                   categorycode => $borrower{categorycode} });
330                 }
331
332                 $imported++;
333                 $template->param('lastimported'=>$borrower{'surname'}.' / '.$borrowernumber);
334             } else {
335                 $invalid++;
336                 push @errors, {unknown_error => 1};
337                 $template->param('lastinvalid'=>$borrower{'surname'}.' / AddMember');
338             }
339         }
340     }
341     (@errors  ) and $template->param(  ERRORS=>\@errors  );
342     (@feedback) and $template->param(FEEDBACK=>\@feedback);
343     $template->param(
344         'uploadborrowers' => 1,
345         'imported'        => $imported,
346         'overwritten'     => $overwritten,
347         'alreadyindb'     => $alreadyindb,
348         'invalid'         => $invalid,
349         'total'           => $imported + $alreadyindb + $invalid + $overwritten,
350     );
351
352 } else {
353     if ($extended) {
354         my @matchpoints = ();
355         my @attr_types = C4::Members::AttributeTypes::GetAttributeTypes(undef, 1);
356         foreach my $type (@attr_types) {
357             my $attr_type = C4::Members::AttributeTypes->fetch($type->{code});
358             if ($attr_type->unique_id()) {
359             push @matchpoints, { code =>  "patron_attribute_" . $attr_type->code(), description => $attr_type->description() };
360             }
361         }
362         $template->param(matchpoints => \@matchpoints);
363     }
364 }
365
366 output_html_with_http_headers $input, $cookie, $template->output;
367