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