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