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