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