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