bug 2287: use defaults when needed even if CSV has correct number of columns
[koha.git] / tools / import_borrowers.pl
1 #!/usr/bin/perl
2
3 # Copyright 2007 Liblime Ltd
4 #
5 # This file is part of Koha.
6 #
7 # Koha is free software; you can redistribute it and/or modify it under the
8 # terms of the GNU General Public License as published by the Free Software
9 # Foundation; either version 2 of the License, or (at your option) any later
10 # version.
11 #
12 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
13 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
14 # A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
15 #
16 # You should have received a copy of the GNU General Public License along with
17 # Koha; if not, write to the Free Software Foundation, Inc., 59 Temple Place,
18 # Suite 330, Boston, MA  02111-1307 USA
19
20 # Script to take some borrowers data in a known format and load it into Koha
21 #
22 # File format
23 #
24 # cardnumber,surname,firstname,title,othernames,initials,streetnumber,streettype,
25 # address line , address line 2, city, zipcode, email, phone, mobile, fax, work email, work phone,
26 # alternate streetnumber, alternate streettype, alternate address line 1, alternate city,
27 # alternate zipcode, alternate email, alternate phone, date of birth, branchcode,
28 # categorycode, enrollment date, expiry date, noaddress, lost, debarred, contact surname,
29 # contact firstname, contact title, borrower notes, contact relationship, ethnicity, ethnicity notes
30 # gender, username, opac note, contact note, password, sort one, sort two
31 #
32 # any fields except cardnumber can be blank but the number of fields must match
33 # dates should be in the format you have set up Koha to expect
34 # branchcode and categorycode need to be valid
35
36 use strict;
37 use warnings;
38
39 use C4::Auth;
40 use C4::Output;
41 use C4::Dates qw(format_date_in_iso);
42 use C4::Context;
43 use C4::Branch qw(GetBranchName);
44 use C4::Members;
45 use C4::Members::Attributes;
46 use C4::Members::AttributeTypes;
47
48 use Text::CSV;
49 # Text::CSV::Unicode, even in binary mode, fails to parse lines with these diacriticals:
50 # ė
51 # č
52
53 use CGI;
54 # use encoding 'utf8';    # don't do this
55
56 my (@errors, @feedback);
57 my $extended = C4::Context->preference('ExtendedPatronAttributes');
58 my @columnkeys = C4::Members->columns;
59 if ($extended) {
60     push @columnkeys, 'patron_attributes';
61 }
62 my $columnkeystpl = [ map { {'key' => $_} }  grep {$_ ne 'borrowernumber' && $_ ne 'cardnumber'} @columnkeys ];  # ref. to array of hashrefs.
63
64 my $input = CGI->new();
65 my $csv   = Text::CSV->new({binary => 1});  # binary needed for non-ASCII Unicode
66 # push @feedback, {feedback=>1, name=>'backend', value=>$csv->backend, backend=>$csv->backend};
67
68 my ( $template, $loggedinuser, $cookie ) = get_template_and_user({
69         template_name   => "tools/import_borrowers.tmpl",
70         query           => $input,
71         type            => "intranet",
72         authnotrequired => 0,
73         flagsrequired   => { tools => 'import_patrons' },
74         debug           => 1,
75 });
76
77 $template->param(columnkeys => $columnkeystpl);
78
79 if ($input->param('sample')) {
80     print $input->header(
81         -type       => 'application/vnd.sun.xml.calc', # 'application/vnd.ms-excel' ?
82         -attachment => 'patron_import.csv',
83     );
84     $csv->combine(@columnkeys);
85     print $csv->string, "\n";
86     exit 1;
87 }
88 my $uploadborrowers = $input->param('uploadborrowers');
89 my $matchpoint      = $input->param('matchpoint');
90 if ($matchpoint) {
91     $matchpoint =~ s/^patron_attribute_//;
92 }
93 my $overwrite_cardnumber = $input->param('overwrite_cardnumber');
94
95 $template->param( SCRIPT_NAME => $ENV{'SCRIPT_NAME'} );
96
97 ($extended) and $template->param(ExtendedPatronAttributes => 1);
98
99 if ( $uploadborrowers && length($uploadborrowers) > 0 ) {
100     push @feedback, {feedback=>1, name=>'filename', value=>$uploadborrowers, filename=>$uploadborrowers};
101     my $handle = $input->upload('uploadborrowers');
102     my $uploadinfo = $input->uploadInfo($uploadborrowers);
103     foreach (keys %$uploadinfo) {
104         push @feedback, {feedback=>1, name=>$_, value=>$uploadinfo->{$_}, $_=>$uploadinfo->{$_}};
105     }
106     my $imported    = 0;
107     my $alreadyindb = 0;
108     my $overwritten = 0;
109     my $invalid     = 0;
110     my $matchpoint_attr_type; 
111     my %defaults = $input->Vars;
112
113     # use header line to construct key to column map
114     my $borrowerline = <$handle>;
115     my $status = $csv->parse($borrowerline);
116     ($status) or push @errors, {badheader=>1,line=>$., lineraw=>$borrowerline};
117     my @csvcolumns = $csv->fields();
118     my %csvkeycol;
119     my $col = 0;
120     foreach my $keycol (@csvcolumns) {
121         # columnkeys don't contain whitespace, but some stupid tools add it
122         $keycol =~ s/ +//g;
123         $csvkeycol{$keycol} = $col++;
124     }
125     #warn($borrowerline);
126     if ($extended) {
127         $matchpoint_attr_type = C4::Members::AttributeTypes->fetch($matchpoint);
128     }
129
130     push @feedback, {feedback=>1, name=>'headerrow', value=>join(', ', @csvcolumns)};
131     my $today_iso = C4::Dates->new()->output('iso');
132     my @criticals = qw(surname branchcode categorycode);    # there probably should be others
133     my @bad_dates;  # I've had a few.
134     my $date_re = C4::Dates->new->regexp('syspref');
135     my  $iso_re = C4::Dates->new->regexp('iso');
136     LINE: while ( my $borrowerline = <$handle> ) {
137         my %borrower;
138         my @missing_criticals;
139         my $patron_attributes;
140         my $status  = $csv->parse($borrowerline);
141         my @columns = $csv->fields();
142         if (! $status) {
143             push @missing_criticals, {badparse=>1, line=>$., lineraw=>$borrowerline};
144         } elsif (@columns == @columnkeys) {
145             @borrower{@columnkeys} = @columns;
146             # MJR: try to fill blanks gracefully by using default values
147             foreach my $key (@criticals) {
148                 if ($borrower{$key} !~ /\S/) {
149                     $borrower{$key} = $defaults{$key};
150                 }
151             } 
152         } else {
153             # MJR: try to recover gracefully by using default values
154             foreach my $key (@columnkeys) {
155                 if (defined($csvkeycol{$key}) and $columns[$csvkeycol{$key}] =~ /\S/) { 
156                     $borrower{$key} = $columns[$csvkeycol{$key}];
157                 } elsif ( $defaults{$key} ) {
158                     $borrower{$key} = $defaults{$key};
159                 } elsif ( scalar grep {$key eq $_} @criticals ) {
160                     # a critical field is undefined
161                     push @missing_criticals, {key=>$key, line=>$., lineraw=>$borrowerline};
162                 } else {
163                         $borrower{$key} = '';
164                 }
165             }
166         }
167         #warn join(':',%borrower);
168         if ($borrower{categorycode}) {
169             push @missing_criticals, {key=>'categorycode', line=>$. , lineraw=>$borrowerline, value=>$borrower{categorycode}, category_map=>1}
170                 unless GetBorrowercategory($borrower{categorycode});
171         } else {
172             push @missing_criticals, {key=>'categorycode', line=>$. , lineraw=>$borrowerline};
173         }
174         if ($borrower{branchcode}) {
175             push @missing_criticals, {key=>'branchcode', line=>$. , lineraw=>$borrowerline, value=>$borrower{branchcode}, branch_map=>1}
176                 unless GetBranchName($borrower{branchcode});
177         } else {
178             push @missing_criticals, {key=>'branchcode', line=>$. , lineraw=>$borrowerline};
179         }
180         if (@missing_criticals) {
181             foreach (@missing_criticals) {
182                 $_->{borrowernumber} = $borrower{borrowernumber} || 'UNDEF';
183                 $_->{surname}        = $borrower{surname} || 'UNDEF';
184             }
185             $invalid++;
186             (25 > scalar @errors) and push @errors, {missing_criticals=>\@missing_criticals};
187             # The first 25 errors are enough.  Keeping track of 30,000+ would destroy performance.
188             next LINE;
189         }
190         my @attrs;
191         if ($extended) {
192             my $attr_str = $borrower{patron_attributes};
193             delete $borrower{patron_attributes};
194             my $ok = $csv->parse($attr_str);
195             my @list = $csv->fields();
196             # FIXME error handling
197             $patron_attributes = [ map { map { my @arr = split /:/, $_, 2; { code => $arr[0], value => $arr[1] } } $_ } @list ];
198         }
199         # Popular spreadsheet applications make it difficult to force date outputs to be zero-padded, but we require it.
200         foreach (qw(dateofbirth dateenrolled dateexpiry)) {
201             my $tempdate = $borrower{$_} or next;
202             if ($tempdate =~ /$date_re/) {
203                 $borrower{$_} = format_date_in_iso($tempdate);
204             } elsif ($tempdate =~ /$iso_re/) {
205                 $borrower{$_} = $tempdate;
206             } else {
207                 $borrower{$_} = '';
208                 push @missing_criticals, {key=>$_, line=>$. , lineraw=>$borrowerline, bad_date=>1};
209             }
210         }
211         $borrower{dateenrolled} = $today_iso unless $borrower{dateenrolled};
212         $borrower{dateexpiry} = GetExpiryDate($borrower{categorycode},$borrower{dateenrolled}) unless $borrower{dateexpiry}; 
213         my $borrowernumber;
214         my $member;
215         if ( ($matchpoint eq 'cardnumber') && ($borrower{'cardnumber'}) ) {
216             $member = GetMember( $borrower{'cardnumber'}, 'cardnumber' );
217             if ($member) {
218                 $borrowernumber = $member->{'borrowernumber'};
219             }
220         } elsif ($extended) {
221             if (defined($matchpoint_attr_type)) {
222                 foreach my $attr (@$patron_attributes) {
223                     if ($attr->{code} eq $matchpoint and $attr->{value} ne '') {
224                         my @borrowernumbers = $matchpoint_attr_type->get_patrons($attr->{value});
225                         $borrowernumber = $borrowernumbers[0] if scalar(@borrowernumbers) == 1;
226                         last;
227                     }
228                 }
229             }
230         }
231             
232         if ($borrowernumber) {
233             # borrower exists
234             unless ($overwrite_cardnumber) {
235                 $alreadyindb++;
236                 $template->param('lastalreadyindb'=>$borrower{'surname'}.' / '.$borrowernumber);
237                 next LINE;
238             }
239             $borrower{'borrowernumber'} = $borrowernumber;
240             for my $col ( keys %borrower) {
241             # use values from extant patron unless our csv file includes this column or we provided a default.
242             # FIXME : You cannot update a field with a  perl-evaluated false value using the defaults.
243             unless(exists($csvkeycol{$col}) || $defaults{$col}) {
244                 $borrower{$col} = $member->{$col} if($member->{$col}) ;
245             }
246         }
247             unless (ModMember(%borrower)) {
248                 $invalid++;
249                 $template->param('lastinvalid'=>$borrower{'surname'}.' / '.$borrowernumber);
250                 next LINE;
251             }
252             if ($extended) {
253                 C4::Members::Attributes::SetBorrowerAttributes($borrower{'borrowernumber'}, $patron_attributes);
254             }
255             $overwritten++;
256             $template->param('lastoverwritten'=>$borrower{'surname'}.' / '.$borrowernumber);
257         } else {
258             # FIXME: fixup_cardnumber says to lock table, but the web interface doesn't so this doesn't either.
259             # At least this is closer to AddMember than in members/memberentry.pl
260             if (!$borrower{'cardnumber'}) {
261                 $borrower{'cardnumber'} = fixup_cardnumber(undef);
262             }
263             if ($borrowernumber = AddMember(%borrower)) {
264                 if ($extended) {
265                     C4::Members::Attributes::SetBorrowerAttributes($borrowernumber, $patron_attributes);
266                 }
267                 $imported++;
268                 $template->param('lastimported'=>$borrower{'surname'}.' / '.$borrowernumber);
269             } else {
270                 $invalid++;             # was just "$invalid", I assume incrementing was the point --atz
271                 $template->param('lastinvalid'=>$borrower{'surname'}.' / AddMember');
272             }
273         }
274     }
275     (@errors  ) and $template->param(  ERRORS=>\@errors  );
276     (@feedback) and $template->param(FEEDBACK=>\@feedback);
277     $template->param(
278         'uploadborrowers' => 1,
279         'imported'        => $imported,
280         'overwritten'     => $overwritten,
281         'alreadyindb'     => $alreadyindb,
282         'invalid'         => $invalid,
283         'total'           => $imported + $alreadyindb + $invalid + $overwritten,
284     );
285
286 } else {
287     if ($extended) {
288         my @matchpoints = ();
289         my @attr_types = C4::Members::AttributeTypes::GetAttributeTypes();
290         foreach my $type (@attr_types) {
291             my $attr_type = C4::Members::AttributeTypes->fetch($type->{code});
292             if ($attr_type->unique_id()) {
293             push @matchpoints, { code =>  "patron_attribute_" . $attr_type->code(), description => $attr_type->description() };
294             }
295         }
296         $template->param(matchpoints => \@matchpoints);
297     }
298 }
299
300 output_html_with_http_headers $input, $cookie, $template->output;
301