Prevent borrower import from overwriting data that it shouldn't, and polish off a...
[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 C4::Auth;
38 use C4::Output;
39 use C4::Dates qw(format_date_in_iso);
40 use C4::Context;
41 use C4::Branch qw(GetBranchName);
42 use C4::Members;
43 use C4::Members::Attributes;
44 use C4::Members::AttributeTypes;
45
46 use Text::CSV;
47 use CGI;
48
49 my @errors;
50 my $extended = C4::Context->preference('ExtendedPatronAttributes');
51 my @columnkeys = C4::Members->columns;
52 if ($extended) {
53     push @columnkeys, 'patron_attributes';
54 }
55 my $columnkeystpl = [ map { {'key' => $_} }  grep {$_ ne 'borrowernumber' && $_ ne 'cardnumber'} @columnkeys ];  # ref. to array of hashrefs.
56
57 my $input = CGI->new();
58 my $csv   = Text::CSV->new();
59
60 my ( $template, $loggedinuser, $cookie ) = get_template_and_user({
61         template_name   => "tools/import_borrowers.tmpl",
62         query           => $input,
63         type            => "intranet",
64         authnotrequired => 0,
65         flagsrequired   => { tools => 'import_patrons' },
66         debug           => 1,
67 });
68
69 $template->param(columnkeys => $columnkeystpl);
70
71 if ($input->param('sample')) {
72     print $input->header(
73         -type       => 'application/vnd.sun.xml.calc', # 'application/vnd.ms-excel' ?
74         -attachment => 'patron_import.csv',
75     );
76     $csv->combine(@columnkeys);
77     print $csv->string, "\n";
78     exit 1;
79 }
80 my $uploadborrowers      = $input->param('uploadborrowers');
81 my $matchpoint           = $input->param('matchpoint');
82 if ($matchpoint) {
83     $matchpoint =~ s/^patron_attribute_//;
84 }
85 my $overwrite_cardnumber = $input->param('overwrite_cardnumber');
86
87 $template->param( SCRIPT_NAME => $ENV{'SCRIPT_NAME'} );
88
89 ($extended) and $template->param(ExtendedPatronAttributes => 1);
90
91 if ( $uploadborrowers && length($uploadborrowers) > 0 ) {
92     my $imported    = 0;
93     my $alreadyindb = 0;
94     my $overwritten = 0;
95     my $invalid     = 0;
96     my $matchpoint_attr_type; 
97     my %defaults = $input->Vars;
98
99     # use header line to construct key to column map
100     my $borrowerline = <$uploadborrowers>;
101     my $status = $csv->parse($borrowerline);
102     ($status) or push @errors, {badheader=>1,line=>$., lineraw=>$borrowerline};
103     my @csvcolumns = $csv->fields();
104     my %csvkeycol;
105     my $col = 0;
106     foreach my $keycol (@csvcolumns) {
107         # columnkeys don't contain whitespace, but some stupid tools add it
108         $keycol =~ s/ +//g;
109         $csvkeycol{$keycol} = $col++;
110     }
111     #warn($borrowerline);
112     if ($extended) {
113         $matchpoint_attr_type = C4::Members::AttributeTypes->fetch($matchpoint);
114     }
115
116     my @criticals = qw(cardnumber surname categorycode);    # there probably should be others
117     my @errors;
118     LINE: while ( my $borrowerline = <$uploadborrowers> ) {
119         my %borrower;
120         my @missing_criticals;
121         my $patron_attributes;
122         my $status  = $csv->parse($borrowerline);
123         my @columns = $csv->fields();
124         if (! $status) {
125             push @missing_criticals, {badparse=>1, line=>$., lineraw=>$borrowerline};
126         } elsif (@columns == @columnkeys) {
127             @borrower{@columnkeys} = @columns;
128         } else {
129             # MJR: try to recover gracefully by using default values
130             foreach my $key (@columnkeys) {
131                 if (defined($csvkeycol{$key}) and $columns[$csvkeycol{$key}] =~ /\S/) { 
132                     $borrower{$key} = $columns[$csvkeycol{$key}];
133                 } elsif ( $defaults{$key} ) {
134                     $borrower{$key} = $defaults{$key};
135                 } elsif ( scalar grep {$key eq $_} @criticals ) {
136                     # a critical field is undefined
137                     push @missing_criticals, {key=>$key, line=>$., lineraw=>$borrowerline};
138                 } else {
139                         $borrower{$key} = '';
140                 }
141             }
142         }
143         #warn join(':',%borrower);
144         push @missing_criticals, {key=>'categorycode' , line=>$. , lineraw=>$borrowerline } unless(  GetBorrowercategory($borrower{categorycode}) );
145         push @missing_criticals, {key=>'branchcode' , line=>$. , lineraw=>$borrowerline } unless(  GetBranchName($borrower{branchcode}) );
146         if (@missing_criticals) {
147             foreach (@missing_criticals) {
148                 $_->{borrowernumber} = $borrower{borrowernumber} || 'UNDEF';
149                 $_->{surname}        = $borrower{surname} || 'UNDEF';
150             }
151             $invalid++;
152             (25 > scalar @errors) and push @errors, {missing_criticals=>\@missing_criticals};
153             # The first 25 errors are enough.  Keeping track of 30,000+ would destroy performance.
154             next LINE;
155         }
156         my @attrs;
157         if ($extended) {
158             my $attr_str = $borrower{patron_attributes};
159             delete $borrower{patron_attributes};
160             my $ok = $csv->parse($attr_str);
161             my @list = $csv->fields();
162             # FIXME error handling
163             $patron_attributes = [ map { map { my @arr = split /:/, $_, 2; { code => $arr[0], value => $arr[1] } } $_ } @list ];
164         }
165         # FIXME date handling.  Popular spreadsheet applications make it difficult to force date outputs to be zero-padded, but we require it.
166         foreach (qw(dateofbirth dateenrolled dateexpiry)) {
167             my $tempdate = $borrower{$_} or next;
168             $borrower{$_} = format_date_in_iso($tempdate) || '';
169         }
170         $borrower{dateenrolled} = C4::Dates->new()->output('iso') unless $borrower{dateenrolled};
171         $borrower{dateexpiry} = GetExpiryDate($borrower{categorycode},$borrower{dateenrolled}) unless $borrower{dateexpiry}; 
172         my $borrowernumber;
173         my $member;
174         if ($matchpoint eq 'cardnumber') {
175             $member = GetMember( $borrower{'cardnumber'}, 'cardnumber' );
176             if ($member) {
177                 $borrowernumber = $member->{'borrowernumber'};
178             }
179         } elsif ($extended) {
180             if (defined($matchpoint_attr_type)) {
181                 foreach my $attr (@$patron_attributes) {
182                     if ($attr->{code} eq $matchpoint and $attr->{value} ne '') {
183                         my @borrowernumbers = $matchpoint_attr_type->get_patrons($attr->{value});
184                         $borrowernumber = $borrowernumbers[0] if scalar(@borrowernumbers) == 1;
185                         last;
186                     }
187                 }
188             }
189         }
190             
191         if ($borrowernumber) {
192             # borrower exists
193             unless ($overwrite_cardnumber) {
194                 $alreadyindb++;
195                 $template->param('lastalreadyindb'=>$borrower{'surname'}.' / '.$borrowernumber);
196                 next LINE;
197             }
198             $borrower{'borrowernumber'} = $borrowernumber;
199             for my $col ( keys %borrower) {
200             # use values from extant patron unless our csv file includes this column or we provided a default.
201             # FIXME : You cannot update a field with a  perl-evaluated false value using the defaults.
202             unless(exists($csvkeycol{$col}) || $defaults{$col}) {
203                 $borrower{$col} = $member->{$col} if($member->{$col}) ;
204             }
205         }
206             unless (ModMember(%borrower)) {
207                 $invalid++;
208                 $template->param('lastinvalid'=>$borrower{'surname'}.' / '.$borrowernumber);
209                 next LINE;
210             }
211             if ($extended) {
212                 C4::Members::Attributes::SetBorrowerAttributes($borrower{'borrowernumber'}, $patron_attributes);
213             }
214             $overwritten++;
215             $template->param('lastoverwritten'=>$borrower{'surname'}.' / '.$borrowernumber);
216         } else {
217             # FIXME: fixup_cardnumber says to lock table, but the web interface doesn't so this doesn't either.
218             # At least this is closer to AddMember than in members/memberentry.pl
219             if (!$borrower{'cardnumber'}) {
220                 $borrower{'cardnumber'} = fixup_cardnumber('');
221             }
222             if ($borrowernumber = AddMember(%borrower)) {
223                 if ($extended) {
224                     C4::Members::Attributes::SetBorrowerAttributes($borrowernumber, $patron_attributes);
225                 }
226                 $imported++;
227                 $template->param('lastimported'=>$borrower{'surname'}.' / '.$borrowernumber);
228             } else {
229                 $invalid++;             # was just "$invalid", I assume incrementing was the point --atz
230                 $template->param('lastinvalid'=>$borrower{'surname'}.' / AddMember');
231             }
232         }
233     }
234     (@errors) and $template->param(ERRORS=>\@errors);
235     $template->param(
236         'uploadborrowers' => 1,
237         'imported'        => $imported,
238         'overwritten'     => $overwritten,
239         'alreadyindb'     => $alreadyindb,
240         'invalid'         => $invalid,
241         'total'           => $imported + $alreadyindb + $invalid + $overwritten,
242     );
243
244 } else {
245     if ($extended) {
246         my @matchpoints = ();
247         my @attr_types = C4::Members::AttributeTypes::GetAttributeTypes();
248         foreach my $type (@attr_types) {
249             my $attr_type = C4::Members::AttributeTypes->fetch($type->{code});
250             if ($attr_type->unique_id()) {
251             push @matchpoints, { code =>  "patron_attribute_" . $attr_type->code(), description => $attr_type->description() };
252             }
253         }
254         $template->param(matchpoints => \@matchpoints);
255     }
256 }
257
258 output_html_with_http_headers $input, $cookie, $template->output;
259