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