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