Bug Fixing : Browse shelves not displaying results
[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
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 our $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     my $ext_preserve = $input->param('ext_preserve') || 0;
127     if ($extended) {
128         $matchpoint_attr_type = C4::Members::AttributeTypes->fetch($matchpoint);
129     }
130
131     push @feedback, {feedback=>1, name=>'headerrow', value=>join(', ', @csvcolumns)};
132     my $today_iso = C4::Dates->new()->output('iso');
133     my @criticals = qw(surname branchcode categorycode);    # there probably should be others
134     my @bad_dates;  # I've had a few.
135     my $date_re = C4::Dates->new->regexp('syspref');
136     my  $iso_re = C4::Dates->new->regexp('iso');
137     LINE: while ( my $borrowerline = <$handle> ) {
138         my %borrower;
139         my @missing_criticals;
140         my $patron_attributes;
141         my $status  = $csv->parse($borrowerline);
142         my @columns = $csv->fields();
143         if (! $status) {
144             push @missing_criticals, {badparse=>1, line=>$., lineraw=>$borrowerline};
145         } elsif (@columns == @columnkeys) {
146             @borrower{@columnkeys} = @columns;
147             # MJR: try to fill blanks gracefully by using default values
148             foreach my $key (@criticals) {
149                 if ($borrower{$key} !~ /\S/) {
150                     $borrower{$key} = $defaults{$key};
151                 }
152             } 
153         } else {
154             # MJR: try to recover gracefully by using default values
155             foreach my $key (@columnkeys) {
156                 if (defined($csvkeycol{$key}) and $columns[$csvkeycol{$key}] =~ /\S/) { 
157                     $borrower{$key} = $columns[$csvkeycol{$key}];
158                 } elsif ( $defaults{$key} ) {
159                     $borrower{$key} = $defaults{$key};
160                 } elsif ( scalar grep {$key eq $_} @criticals ) {
161                     # a critical field is undefined
162                     push @missing_criticals, {key=>$key, line=>$., lineraw=>$borrowerline};
163                 } else {
164                         $borrower{$key} = '';
165                 }
166             }
167         }
168         #warn join(':',%borrower);
169         if ($borrower{categorycode}) {
170             push @missing_criticals, {key=>'categorycode', line=>$. , lineraw=>$borrowerline, value=>$borrower{categorycode}, category_map=>1}
171                 unless GetBorrowercategory($borrower{categorycode});
172         } else {
173             push @missing_criticals, {key=>'categorycode', line=>$. , lineraw=>$borrowerline};
174         }
175         if ($borrower{branchcode}) {
176             push @missing_criticals, {key=>'branchcode', line=>$. , lineraw=>$borrowerline, value=>$borrower{branchcode}, branch_map=>1}
177                 unless GetBranchName($borrower{branchcode});
178         } else {
179             push @missing_criticals, {key=>'branchcode', line=>$. , lineraw=>$borrowerline};
180         }
181         if (@missing_criticals) {
182             foreach (@missing_criticals) {
183                 $_->{borrowernumber} = $borrower{borrowernumber} || 'UNDEF';
184                 $_->{surname}        = $borrower{surname} || 'UNDEF';
185             }
186             $invalid++;
187             (25 > scalar @errors) and push @errors, {missing_criticals=>\@missing_criticals};
188             # The first 25 errors are enough.  Keeping track of 30,000+ would destroy performance.
189             next LINE;
190         }
191         if ($extended) {
192             my $attr_str = $borrower{patron_attributes};
193             delete $borrower{patron_attributes};    # not really a field in borrowers, so we don't want to pass it to ModMember.
194             $patron_attributes = extended_attributes_code_value_arrayref($attr_str); 
195         }
196         # Popular spreadsheet applications make it difficult to force date outputs to be zero-padded, but we require it.
197         foreach (qw(dateofbirth dateenrolled dateexpiry)) {
198             my $tempdate = $borrower{$_} or next;
199             if ($tempdate =~ /$date_re/) {
200                 $borrower{$_} = format_date_in_iso($tempdate);
201             } elsif ($tempdate =~ /$iso_re/) {
202                 $borrower{$_} = $tempdate;
203             } else {
204                 $borrower{$_} = '';
205                 push @missing_criticals, {key=>$_, line=>$. , lineraw=>$borrowerline, bad_date=>1};
206             }
207         }
208         $borrower{dateenrolled} = $today_iso unless $borrower{dateenrolled};
209         $borrower{dateexpiry} = GetExpiryDate($borrower{categorycode},$borrower{dateenrolled}) unless $borrower{dateexpiry}; 
210         my $borrowernumber;
211         my $member;
212         if ( ($matchpoint eq 'cardnumber') && ($borrower{'cardnumber'}) ) {
213             $member = GetMember( $borrower{'cardnumber'}, 'cardnumber' );
214             if ($member) {
215                 $borrowernumber = $member->{'borrowernumber'};
216             }
217         } elsif ($extended) {
218             if (defined($matchpoint_attr_type)) {
219                 foreach my $attr (@$patron_attributes) {
220                     if ($attr->{code} eq $matchpoint and $attr->{value} ne '') {
221                         my @borrowernumbers = $matchpoint_attr_type->get_patrons($attr->{value});
222                         $borrowernumber = $borrowernumbers[0] if scalar(@borrowernumbers) == 1;
223                         last;
224                     }
225                 }
226             }
227         }
228             
229         if ($borrowernumber) {
230             # borrower exists
231             unless ($overwrite_cardnumber) {
232                 $alreadyindb++;
233                 $template->param('lastalreadyindb'=>$borrower{'surname'}.' / '.$borrowernumber);
234                 next LINE;
235             }
236             $borrower{'borrowernumber'} = $borrowernumber;
237             for my $col (keys %borrower) {
238                 # use values from extant patron unless our csv file includes this column or we provided a default.
239                 # FIXME : You cannot update a field with a  perl-evaluated false value using the defaults.
240                 unless(exists($csvkeycol{$col}) || $defaults{$col}) {
241                     $borrower{$col} = $member->{$col} if($member->{$col}) ;
242                 }
243             }
244             unless (ModMember(%borrower)) {
245                 $invalid++;
246                 $template->param('lastinvalid'=>$borrower{'surname'}.' / '.$borrowernumber);
247                 next LINE;
248             }
249             if ($extended) {
250                 if ($ext_preserve) {
251                     my $old_attributes = GetBorrowerAttributes($borrowernumber);
252                     $patron_attributes = extended_attributes_merge($old_attributes, $patron_attributes);  #TODO: expose repeatable options in template
253                 }
254                 SetBorrowerAttributes($borrower{'borrowernumber'}, $patron_attributes);
255             }
256             $overwritten++;
257             $template->param('lastoverwritten'=>$borrower{'surname'}.' / '.$borrowernumber);
258         } else {
259             # FIXME: fixup_cardnumber says to lock table, but the web interface doesn't so this doesn't either.
260             # At least this is closer to AddMember than in members/memberentry.pl
261             if (!$borrower{'cardnumber'}) {
262                 $borrower{'cardnumber'} = fixup_cardnumber(undef);
263             }
264             if ($borrowernumber = AddMember(%borrower)) {
265                 if ($extended) {
266                     SetBorrowerAttributes($borrowernumber, $patron_attributes);
267                 }
268                 $imported++;
269                 $template->param('lastimported'=>$borrower{'surname'}.' / '.$borrowernumber);
270             } else {
271                 $invalid++;
272                 $template->param('lastinvalid'=>$borrower{'surname'}.' / AddMember');
273             }
274         }
275     }
276     (@errors  ) and $template->param(  ERRORS=>\@errors  );
277     (@feedback) and $template->param(FEEDBACK=>\@feedback);
278     $template->param(
279         'uploadborrowers' => 1,
280         'imported'        => $imported,
281         'overwritten'     => $overwritten,
282         'alreadyindb'     => $alreadyindb,
283         'invalid'         => $invalid,
284         'total'           => $imported + $alreadyindb + $invalid + $overwritten,
285     );
286
287 } else {
288     if ($extended) {
289         my @matchpoints = ();
290         my @attr_types = C4::Members::AttributeTypes::GetAttributeTypes();
291         foreach my $type (@attr_types) {
292             my $attr_type = C4::Members::AttributeTypes->fetch($type->{code});
293             if ($attr_type->unique_id()) {
294             push @matchpoints, { code =>  "patron_attribute_" . $attr_type->code(), description => $attr_type->description() };
295             }
296         }
297         $template->param(matchpoints => \@matchpoints);
298     }
299 }
300
301 output_html_with_http_headers $input, $cookie, $template->output;
302