Bug 15451: Better error handling
[koha.git] / tools / import_borrowers.pl
blobe1754e6efef4d02b87cd5a313e9f74c17b9272a9
1 #!/usr/bin/perl
3 # Copyright 2007 Liblime
4 # Parts copyright 2010 BibLibre
6 # This file is part of Koha.
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.
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.
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>.
21 # Script to take some borrowers data in a known format and load it into Koha
23 # File format
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
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
37 use strict;
38 use warnings;
40 use C4::Auth;
41 use C4::Output;
42 use C4::Context;
43 use C4::Branch qw/GetBranchesLoop GetBranchName/;
44 use C4::Members;
45 use C4::Members::Attributes qw(:all);
46 use C4::Members::AttributeTypes;
47 use C4::Members::Messaging;
48 use C4::Reports::Guided;
49 use C4::Templates;
50 use Koha::Patron::Debarments;
51 use Koha::Patrons;
52 use Koha::DateUtils;
54 use Text::CSV;
55 # Text::CSV::Unicode, even in binary mode, fails to parse lines with these diacriticals:
56 # ė
57 # č
59 use CGI qw ( -utf8 );
60 # use encoding 'utf8'; # don't do this
62 my (@errors, @feedback);
63 my $extended = C4::Context->preference('ExtendedPatronAttributes');
64 my $set_messaging_prefs = C4::Context->preference('EnhancedMessagingPreferences');
65 my @columnkeys = Koha::Patrons->columns();
66 @columnkeys = map { $_ ne 'borrowernumber' ? $_ : () } @columnkeys;
67 if ($extended) {
68 push @columnkeys, 'patron_attributes';
71 my $input = CGI->new();
72 our $csv = Text::CSV->new({binary => 1}); # binary needed for non-ASCII Unicode
73 #push @feedback, {feedback=>1, name=>'backend', value=>$csv->backend, backend=>$csv->backend}; #XXX
75 my ( $template, $loggedinuser, $cookie ) = get_template_and_user({
76 template_name => "tools/import_borrowers.tt",
77 query => $input,
78 type => "intranet",
79 authnotrequired => 0,
80 flagsrequired => { tools => 'import_patrons' },
81 debug => 1,
82 });
84 # get the branches and pass them to the template
85 my $branches = GetBranchesLoop();
86 $template->param( branches => $branches ) if ( $branches );
87 # get the patron categories and pass them to the template
88 my $categories = GetBorrowercategoryList();
89 $template->param( categories => $categories ) if ( $categories );
90 my $columns = C4::Templates::GetColumnDefs( $input )->{borrowers};
91 $columns = [ grep { $_->{field} ne 'borrowernumber' ? $_ : () } @$columns ];
92 $template->param( borrower_fields => $columns );
94 if ($input->param('sample')) {
95 print $input->header(
96 -type => 'application/vnd.sun.xml.calc', # 'application/vnd.ms-excel' ?
97 -attachment => 'patron_import.csv',
99 $csv->combine(@columnkeys);
100 print $csv->string, "\n";
101 exit 0;
103 my $uploadborrowers = $input->param('uploadborrowers');
104 my $matchpoint = $input->param('matchpoint');
105 if ($matchpoint) {
106 $matchpoint =~ s/^patron_attribute_//;
108 my $overwrite_cardnumber = $input->param('overwrite_cardnumber');
110 $template->param( SCRIPT_NAME => '/cgi-bin/koha/tools/import_borrowers.pl' );
112 if ( $uploadborrowers && length($uploadborrowers) > 0 ) {
113 push @feedback, {feedback=>1, name=>'filename', value=>$uploadborrowers, filename=>$uploadborrowers};
114 my $handle = $input->upload('uploadborrowers');
115 my $uploadinfo = $input->uploadInfo($uploadborrowers);
116 foreach (keys %$uploadinfo) {
117 push @feedback, {feedback=>1, name=>$_, value=>$uploadinfo->{$_}, $_=>$uploadinfo->{$_}};
119 my $imported = 0;
120 my $alreadyindb = 0;
121 my $overwritten = 0;
122 my $invalid = 0;
123 my $matchpoint_attr_type;
124 my %defaults = $input->Vars;
126 # use header line to construct key to column map
127 my $borrowerline = <$handle>;
128 my $status = $csv->parse($borrowerline);
129 ($status) or push @errors, {badheader=>1,line=>$., lineraw=>$borrowerline};
130 my @csvcolumns = $csv->fields();
131 my %csvkeycol;
132 my $col = 0;
133 foreach my $keycol (@csvcolumns) {
134 # columnkeys don't contain whitespace, but some stupid tools add it
135 $keycol =~ s/ +//g;
136 $csvkeycol{$keycol} = $col++;
138 #warn($borrowerline);
139 my $ext_preserve = $input->param('ext_preserve') || 0;
140 if ($extended) {
141 $matchpoint_attr_type = C4::Members::AttributeTypes->fetch($matchpoint);
144 push @feedback, {feedback=>1, name=>'headerrow', value=>join(', ', @csvcolumns)};
145 my $today_iso = output_pref( { dt => dt_from_string, dateonly => 1, dateformat => 'iso' });
146 my @criticals = qw(surname branchcode categorycode); # there probably should be others
147 my @bad_dates; # I've had a few.
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};
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} = '';
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};
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};
192 if (@missing_criticals) {
193 foreach (@missing_criticals) {
194 $_->{borrowernumber} = $borrower{borrowernumber} || 'UNDEF';
195 $_->{surname} = $borrower{surname} || 'UNDEF';
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;
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);
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 $tempdate = eval { output_pref( { dt => dt_from_string( $tempdate ), dateonly => 1, dateformat => 'iso' } ); };
214 if ($tempdate) {
215 $borrower{$_} = $tempdate;
216 } else {
217 $borrower{$_} = '';
218 push @missing_criticals, {key=>$_, line=>$. , lineraw=>$borrowerline, bad_date=>1};
221 $borrower{dateenrolled} = $today_iso unless $borrower{dateenrolled};
222 $borrower{dateexpiry} = GetExpiryDate($borrower{categorycode},$borrower{dateenrolled}) unless $borrower{dateexpiry};
223 my $borrowernumber;
224 my $member;
225 if ( ($matchpoint eq 'cardnumber') && ($borrower{'cardnumber'}) ) {
226 $member = GetMember( 'cardnumber' => $borrower{'cardnumber'} );
227 if ($member) {
228 $borrowernumber = $member->{'borrowernumber'};
230 } elsif ( ($matchpoint eq 'userid') && ($borrower{'userid'}) ) {
231 $member = GetMember( 'userid' => $borrower{'userid'} );
232 if ($member) {
233 $borrowernumber = $member->{'borrowernumber'};
235 } elsif ($extended) {
236 if (defined($matchpoint_attr_type)) {
237 foreach my $attr (@$patron_attributes) {
238 if ($attr->{code} eq $matchpoint and $attr->{value} ne '') {
239 my @borrowernumbers = $matchpoint_attr_type->get_patrons($attr->{value});
240 $borrowernumber = $borrowernumbers[0] if scalar(@borrowernumbers) == 1;
241 last;
247 if ( C4::Members::checkcardnumber( $borrower{cardnumber}, $borrowernumber ) ) {
248 push @errors, {
249 invalid_cardnumber => 1,
250 borrowernumber => $borrowernumber,
251 cardnumber => $borrower{cardnumber}
253 $invalid++;
254 next;
257 if ($borrowernumber) {
258 # borrower exists
259 unless ($overwrite_cardnumber) {
260 $alreadyindb++;
261 $template->param('lastalreadyindb'=>$borrower{'surname'}.' / '.$borrowernumber);
262 next LINE;
264 $borrower{'borrowernumber'} = $borrowernumber;
265 for my $col (keys %borrower) {
266 # use values from extant patron unless our csv file includes this column or we provided a default.
267 # FIXME : You cannot update a field with a perl-evaluated false value using the defaults.
269 # The password is always encrypted, skip it!
270 next if $col eq 'password';
272 unless(exists($csvkeycol{$col}) || $defaults{$col}) {
273 $borrower{$col} = $member->{$col} if($member->{$col}) ;
277 # Check if the userid provided does not exist yet
278 if ( exists $borrower{userid}
279 and $borrower{userid}
280 and not Check_Userid( $borrower{userid}, $borrower{borrowernumber} ) ) {
281 push @errors, { duplicate_userid => 1, userid => $borrower{userid} };
282 $invalid++;
283 next LINE;
286 unless (ModMember(%borrower)) {
287 $invalid++;
288 # until we have better error trapping, we have no way of knowing why ModMember errored out...
289 push @errors, {unknown_error => 1};
290 $template->param('lastinvalid'=>$borrower{'surname'}.' / '.$borrowernumber);
291 next LINE;
294 # Don't add a new restriction if the existing 'combined' restriction matches this one
295 if ( $borrower{debarred} && ( ( $borrower{debarred} ne $member->{debarred} ) || ( $borrower{debarredcomment} ne $member->{debarredcomment} ) ) ) {
296 # Check to see if this debarment already exists
297 my $debarrments = GetDebarments(
299 borrowernumber => $borrowernumber,
300 expiration => $borrower{debarred},
301 comment => $borrower{debarredcomment}
304 # If it doesn't, then add it!
305 unless (@$debarrments) {
306 AddDebarment(
308 borrowernumber => $borrowernumber,
309 expiration => $borrower{debarred},
310 comment => $borrower{debarredcomment}
316 if ($extended) {
317 if ($ext_preserve) {
318 my $old_attributes = GetBorrowerAttributes($borrowernumber);
319 $patron_attributes = extended_attributes_merge($old_attributes, $patron_attributes); #TODO: expose repeatable options in template
321 push @errors, {unknown_error => 1} unless SetBorrowerAttributes($borrower{'borrowernumber'}, $patron_attributes, 'no_branch_limit' );
323 $overwritten++;
324 $template->param('lastoverwritten'=>$borrower{'surname'}.' / '.$borrowernumber);
325 } else {
326 # FIXME: fixup_cardnumber says to lock table, but the web interface doesn't so this doesn't either.
327 # At least this is closer to AddMember than in members/memberentry.pl
328 if (!$borrower{'cardnumber'}) {
329 $borrower{'cardnumber'} = fixup_cardnumber(undef);
331 if ($borrowernumber = AddMember(%borrower)) {
333 if ( $borrower{debarred} ) {
334 AddDebarment(
336 borrowernumber => $borrowernumber,
337 expiration => $borrower{debarred},
338 comment => $borrower{debarredcomment}
343 if ($extended) {
344 SetBorrowerAttributes($borrowernumber, $patron_attributes);
347 if ($set_messaging_prefs) {
348 C4::Members::Messaging::SetMessagingPreferencesFromDefaults({ borrowernumber => $borrowernumber,
349 categorycode => $borrower{categorycode} });
352 $imported++;
353 $template->param('lastimported'=>$borrower{'surname'}.' / '.$borrowernumber);
354 } else {
355 $invalid++;
356 push @errors, {unknown_error => 1};
357 $template->param('lastinvalid'=>$borrower{'surname'}.' / AddMember');
361 (@errors ) and $template->param( ERRORS=>\@errors );
362 (@feedback) and $template->param(FEEDBACK=>\@feedback);
363 $template->param(
364 'uploadborrowers' => 1,
365 'imported' => $imported,
366 'overwritten' => $overwritten,
367 'alreadyindb' => $alreadyindb,
368 'invalid' => $invalid,
369 'total' => $imported + $alreadyindb + $invalid + $overwritten,
372 } else {
373 if ($extended) {
374 my @matchpoints = ();
375 my @attr_types = C4::Members::AttributeTypes::GetAttributeTypes(undef, 1);
376 foreach my $type (@attr_types) {
377 my $attr_type = C4::Members::AttributeTypes->fetch($type->{code});
378 if ($attr_type->unique_id()) {
379 push @matchpoints, { code => "patron_attribute_" . $attr_type->code(), description => $attr_type->description() };
382 $template->param(matchpoints => \@matchpoints);
386 output_html_with_http_headers $input, $cookie, $template->output;