Allow option to preserve Extended Attributes on patron import update.
[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 qw(:all);
46 use C4::Members::AttributeTypes;
47 use C4::Members::Messaging;
48
49 use Text::CSV;
50 # Text::CSV::Unicode, even in binary mode, fails to parse lines with these diacriticals:
51 # ė
52 # č
53
54 use CGI;
55 # use encoding 'utf8';    # don't do this
56
57 my (@errors, @feedback);
58 my $extended = C4::Context->preference('ExtendedPatronAttributes');
59 my $set_messaging_prefs = C4::Context->preference('EnhancedMessagingPreferences');
60 my @columnkeys = C4::Members->columns;
61 if ($extended) {
62     push @columnkeys, 'patron_attributes';
63 }
64 my $columnkeystpl = [ map { {'key' => $_} }  grep {$_ ne 'borrowernumber' && $_ ne 'cardnumber'} @columnkeys ];  # ref. to array of hashrefs.
65
66 my $input = CGI->new();
67 our $csv  = Text::CSV->new({binary => 1});  # binary needed for non-ASCII Unicode
68 # push @feedback, {feedback=>1, name=>'backend', value=>$csv->backend, backend=>$csv->backend};
69
70 my ( $template, $loggedinuser, $cookie ) = get_template_and_user({
71         template_name   => "tools/import_borrowers.tmpl",
72         query           => $input,
73         type            => "intranet",
74         authnotrequired => 0,
75         flagsrequired   => { tools => 'import_patrons' },
76         debug           => 1,
77 });
78
79 $template->param(columnkeys => $columnkeystpl);
80
81 if ($input->param('sample')) {
82     print $input->header(
83         -type       => 'application/vnd.sun.xml.calc', # 'application/vnd.ms-excel' ?
84         -attachment => 'patron_import.csv',
85     );
86     $csv->combine(@columnkeys);
87     print $csv->string, "\n";
88     exit 1;
89 }
90 my $uploadborrowers = $input->param('uploadborrowers');
91 my $matchpoint      = $input->param('matchpoint');
92 if ($matchpoint) {
93     $matchpoint =~ s/^patron_attribute_//;
94 }
95 my $overwrite_cardnumber = $input->param('overwrite_cardnumber');
96
97 $template->param( SCRIPT_NAME => $ENV{'SCRIPT_NAME'} );
98
99 ($extended) and $template->param(ExtendedPatronAttributes => 1);
100
101 if ( $uploadborrowers && length($uploadborrowers) > 0 ) {
102     push @feedback, {feedback=>1, name=>'filename', value=>$uploadborrowers, filename=>$uploadborrowers};
103     my $handle = $input->upload('uploadborrowers');
104     my $uploadinfo = $input->uploadInfo($uploadborrowers);
105     foreach (keys %$uploadinfo) {
106         push @feedback, {feedback=>1, name=>$_, value=>$uploadinfo->{$_}, $_=>$uploadinfo->{$_}};
107     }
108     my $imported    = 0;
109     my $alreadyindb = 0;
110     my $overwritten = 0;
111     my $invalid     = 0;
112     my $matchpoint_attr_type; 
113     my %defaults = $input->Vars;
114
115     # use header line to construct key to column map
116     my $borrowerline = <$handle>;
117     my $status = $csv->parse($borrowerline);
118     ($status) or push @errors, {badheader=>1,line=>$., lineraw=>$borrowerline};
119     my @csvcolumns = $csv->fields();
120     my %csvkeycol;
121     my $col = 0;
122     foreach my $keycol (@csvcolumns) {
123         # columnkeys don't contain whitespace, but some stupid tools add it
124         $keycol =~ s/ +//g;
125         $csvkeycol{$keycol} = $col++;
126     }
127     #warn($borrowerline);
128     my $ext_preserve = $input->param('ext_preserve') || 0;
129     if ($extended) {
130         $matchpoint_attr_type = C4::Members::AttributeTypes->fetch($matchpoint);
131     }
132
133     push @feedback, {feedback=>1, name=>'headerrow', value=>join(', ', @csvcolumns)};
134     my $today_iso = C4::Dates->new()->output('iso');
135     my @criticals = qw(surname branchcode categorycode);    # there probably should be others
136     my @bad_dates;  # I've had a few.
137     my $date_re = C4::Dates->new->regexp('syspref');
138     my  $iso_re = C4::Dates->new->regexp('iso');
139     LINE: while ( my $borrowerline = <$handle> ) {
140         my %borrower;
141         my @missing_criticals;
142         my $patron_attributes;
143         my $status  = $csv->parse($borrowerline);
144         my @columns = $csv->fields();
145         if (! $status) {
146             push @missing_criticals, {badparse=>1, line=>$., lineraw=>$borrowerline};
147         } elsif (@columns == @columnkeys) {
148             @borrower{@columnkeys} = @columns;
149             # MJR: try to fill blanks gracefully by using default values
150             foreach my $key (@criticals) {
151                 if ($borrower{$key} !~ /\S/) {
152                     $borrower{$key} = $defaults{$key};
153                 }
154             } 
155         } else {
156             # MJR: try to recover gracefully by using default values
157             foreach my $key (@columnkeys) {
158                 if (defined($csvkeycol{$key}) and $columns[$csvkeycol{$key}] =~ /\S/) { 
159                     $borrower{$key} = $columns[$csvkeycol{$key}];
160                 } elsif ( $defaults{$key} ) {
161                     $borrower{$key} = $defaults{$key};
162                 } elsif ( scalar grep {$key eq $_} @criticals ) {
163                     # a critical field is undefined
164                     push @missing_criticals, {key=>$key, line=>$., lineraw=>$borrowerline};
165                 } else {
166                         $borrower{$key} = '';
167                 }
168             }
169         }
170         #warn join(':',%borrower);
171         if ($borrower{categorycode}) {
172             push @missing_criticals, {key=>'categorycode', line=>$. , lineraw=>$borrowerline, value=>$borrower{categorycode}, category_map=>1}
173                 unless GetBorrowercategory($borrower{categorycode});
174         } else {
175             push @missing_criticals, {key=>'categorycode', line=>$. , lineraw=>$borrowerline};
176         }
177         if ($borrower{branchcode}) {
178             push @missing_criticals, {key=>'branchcode', line=>$. , lineraw=>$borrowerline, value=>$borrower{branchcode}, branch_map=>1}
179                 unless GetBranchName($borrower{branchcode});
180         } else {
181             push @missing_criticals, {key=>'branchcode', line=>$. , lineraw=>$borrowerline};
182         }
183         if (@missing_criticals) {
184             foreach (@missing_criticals) {
185                 $_->{borrowernumber} = $borrower{borrowernumber} || 'UNDEF';
186                 $_->{surname}        = $borrower{surname} || 'UNDEF';
187             }
188             $invalid++;
189             (25 > scalar @errors) and push @errors, {missing_criticals=>\@missing_criticals};
190             # The first 25 errors are enough.  Keeping track of 30,000+ would destroy performance.
191             next LINE;
192         }
193         if ($extended) {
194             my $attr_str = $borrower{patron_attributes};
195             delete $borrower{patron_attributes};    # not really a field in borrowers, so we don't want to pass it to ModMember.
196             $patron_attributes = extended_attributes_code_value_arrayref($attr_str); 
197         }
198         # Popular spreadsheet applications make it difficult to force date outputs to be zero-padded, but we require it.
199         foreach (qw(dateofbirth dateenrolled dateexpiry)) {
200             my $tempdate = $borrower{$_} or next;
201             if ($tempdate =~ /$date_re/) {
202                 $borrower{$_} = format_date_in_iso($tempdate);
203             } elsif ($tempdate =~ /$iso_re/) {
204                 $borrower{$_} = $tempdate;
205             } else {
206                 $borrower{$_} = '';
207                 push @missing_criticals, {key=>$_, line=>$. , lineraw=>$borrowerline, bad_date=>1};
208             }
209         }
210         $borrower{dateenrolled} = $today_iso unless $borrower{dateenrolled};
211         $borrower{dateexpiry} = GetExpiryDate($borrower{categorycode},$borrower{dateenrolled}) unless $borrower{dateexpiry}; 
212         my $borrowernumber;
213         my $member;
214         if ( ($matchpoint eq 'cardnumber') && ($borrower{'cardnumber'}) ) {
215             $member = GetMember( $borrower{'cardnumber'}, 'cardnumber' );
216             if ($member) {
217                 $borrowernumber = $member->{'borrowernumber'};
218             }
219         } elsif ($extended) {
220             if (defined($matchpoint_attr_type)) {
221                 foreach my $attr (@$patron_attributes) {
222                     if ($attr->{code} eq $matchpoint and $attr->{value} ne '') {
223                         my @borrowernumbers = $matchpoint_attr_type->get_patrons($attr->{value});
224                         $borrowernumber = $borrowernumbers[0] if scalar(@borrowernumbers) == 1;
225                         last;
226                     }
227                 }
228             }
229         }
230             
231         if ($borrowernumber) {
232             # borrower exists
233             unless ($overwrite_cardnumber) {
234                 $alreadyindb++;
235                 $template->param('lastalreadyindb'=>$borrower{'surname'}.' / '.$borrowernumber);
236                 next LINE;
237             }
238             $borrower{'borrowernumber'} = $borrowernumber;
239             for my $col (keys %borrower) {
240                 # use values from extant patron unless our csv file includes this column or we provided a default.
241                 # FIXME : You cannot update a field with a  perl-evaluated false value using the defaults.
242                 unless(exists($csvkeycol{$col}) || $defaults{$col}) {
243                     $borrower{$col} = $member->{$col} if($member->{$col}) ;
244                 }
245             }
246             unless (ModMember(%borrower)) {
247                 $invalid++;
248                 $template->param('lastinvalid'=>$borrower{'surname'}.' / '.$borrowernumber);
249                 next LINE;
250             }
251             if ($extended) {
252                 if ($ext_preserve) {
253                     my $old_attributes = GetBorrowerAttributes($borrowernumber);
254                     $patron_attributes = extended_attributes_merge($old_attributes, $patron_attributes);  #TODO: expose repeatable options in template
255                 }
256                 SetBorrowerAttributes($borrower{'borrowernumber'}, $patron_attributes);
257             }
258             $overwritten++;
259             $template->param('lastoverwritten'=>$borrower{'surname'}.' / '.$borrowernumber);
260         } else {
261             # FIXME: fixup_cardnumber says to lock table, but the web interface doesn't so this doesn't either.
262             # At least this is closer to AddMember than in members/memberentry.pl
263             if (!$borrower{'cardnumber'}) {
264                 $borrower{'cardnumber'} = fixup_cardnumber(undef);
265             }
266             if ($borrowernumber = AddMember(%borrower)) {
267                 if ($extended) {
268                     SetBorrowerAttributes($borrowernumber, $patron_attributes);
269                 }
270                 if ($set_messaging_prefs) {
271                     C4::Members::Messaging::SetMessagingPreferencesFromDefaults({ borrowernumber => $borrowernumber,
272                                                                                   categorycode => $borrower{categorycode} });
273                 }
274                 $imported++;
275                 $template->param('lastimported'=>$borrower{'surname'}.' / '.$borrowernumber);
276             } else {
277                 $invalid++;
278                 $template->param('lastinvalid'=>$borrower{'surname'}.' / AddMember');
279             }
280         }
281     }
282     (@errors  ) and $template->param(  ERRORS=>\@errors  );
283     (@feedback) and $template->param(FEEDBACK=>\@feedback);
284     $template->param(
285         'uploadborrowers' => 1,
286         'imported'        => $imported,
287         'overwritten'     => $overwritten,
288         'alreadyindb'     => $alreadyindb,
289         'invalid'         => $invalid,
290         'total'           => $imported + $alreadyindb + $invalid + $overwritten,
291     );
292
293 } else {
294     if ($extended) {
295         my @matchpoints = ();
296         my @attr_types = C4::Members::AttributeTypes::GetAttributeTypes();
297         foreach my $type (@attr_types) {
298             my $attr_type = C4::Members::AttributeTypes->fetch($type->{code});
299             if ($attr_type->unique_id()) {
300             push @matchpoints, { code =>  "patron_attribute_" . $attr_type->code(), description => $attr_type->description() };
301             }
302         }
303         $template->param(matchpoints => \@matchpoints);
304     }
305 }
306
307 output_html_with_http_headers $input, $cookie, $template->output;
308