3 # Copyright 2007 Liblime
4 # Parts copyright 2010 BibLibre
6 # This file is part of Koha.
8 # Koha is free software; you can redistribute it and/or modify it under the
9 # terms of the GNU General Public License as published by the Free Software
10 # Foundation; either version 2 of the License, or (at your option) any later
13 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
14 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
15 # A PARTICULAR PURPOSE. See the GNU General Public License for more details.
17 # You should have received a copy of the GNU General Public License along
18 # with Koha; if not, write to the Free Software Foundation, Inc.,
19 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
21 # Script to take some borrowers data in a known format and load it into Koha
25 # cardnumber,surname,firstname,title,othernames,initials,streetnumber,streettype,
26 # address line , address line 2, city, zipcode, contry, email, phone, mobile, fax, work email, work phone,
27 # alternate streetnumber, alternate streettype, alternate address line 1, alternate city,
28 # alternate zipcode, alternate country, alternate email, alternate phone, date of birth, branchcode,
29 # categorycode, enrollment date, expiry date, noaddress, lost, debarred, contact surname,
30 # contact firstname, contact title, borrower notes, contact relationship, ethnicity, ethnicity notes
31 # gender, username, opac note, contact note, password, sort one, sort two
33 # any fields except cardnumber can be blank but the number of fields must match
34 # dates should be in the format you have set up Koha to expect
35 # branchcode and categorycode need to be valid
42 use C4::Dates qw(format_date_in_iso);
44 use C4::Branch qw/GetBranchesLoop GetBranchName/;
46 use C4::Members::Attributes qw(:all);
47 use C4::Members::AttributeTypes;
48 use C4::Members::Messaging;
49 use C4::Reports::Guided;
51 use Koha::Borrower::Debarments;
54 # Text::CSV::Unicode, even in binary mode, fails to parse lines with these diacriticals:
59 # use encoding 'utf8'; # don't do this
61 my (@errors, @feedback);
62 my $extended = C4::Context->preference('ExtendedPatronAttributes');
63 my $set_messaging_prefs = C4::Context->preference('EnhancedMessagingPreferences');
64 my @columnkeys = C4::Members::columns();
66 push @columnkeys, 'patron_attributes';
69 my $input = CGI->new();
70 our $csv = Text::CSV->new({binary => 1}); # binary needed for non-ASCII Unicode
71 #push @feedback, {feedback=>1, name=>'backend', value=>$csv->backend, backend=>$csv->backend}; #XXX
73 my ( $template, $loggedinuser, $cookie ) = get_template_and_user({
74 template_name => "tools/import_borrowers.tt",
78 flagsrequired => { tools => 'import_patrons' },
82 # get the branches and pass them to the template
83 my $branches = GetBranchesLoop();
84 $template->param( branches => $branches ) if ( $branches );
85 # get the patron categories and pass them to the template
86 my $categories = GetBorrowercategoryList();
87 $template->param( categories => $categories ) if ( $categories );
88 my $columns = C4::Templates::GetColumnDefs( $input )->{borrowers};
89 $columns = [ grep { $_->{field} ne 'borrowernumber' ? $_ : () } @$columns ];
90 $template->param( borrower_fields => $columns );
92 if ($input->param('sample')) {
94 -type => 'application/vnd.sun.xml.calc', # 'application/vnd.ms-excel' ?
95 -attachment => 'patron_import.csv',
97 $csv->combine(@columnkeys);
98 print $csv->string, "\n";
101 my $uploadborrowers = $input->param('uploadborrowers');
102 my $matchpoint = $input->param('matchpoint');
104 $matchpoint =~ s/^patron_attribute_//;
106 my $overwrite_cardnumber = $input->param('overwrite_cardnumber');
108 $template->param( SCRIPT_NAME => $ENV{'SCRIPT_NAME'} );
110 if ( $uploadborrowers && length($uploadborrowers) > 0 ) {
111 push @feedback, {feedback=>1, name=>'filename', value=>$uploadborrowers, filename=>$uploadborrowers};
112 my $handle = $input->upload('uploadborrowers');
113 my $uploadinfo = $input->uploadInfo($uploadborrowers);
114 foreach (keys %$uploadinfo) {
115 push @feedback, {feedback=>1, name=>$_, value=>$uploadinfo->{$_}, $_=>$uploadinfo->{$_}};
121 my $matchpoint_attr_type;
122 my %defaults = $input->Vars;
124 # use header line to construct key to column map
125 my $borrowerline = <$handle>;
126 my $status = $csv->parse($borrowerline);
127 ($status) or push @errors, {badheader=>1,line=>$., lineraw=>$borrowerline};
128 my @csvcolumns = $csv->fields();
131 foreach my $keycol (@csvcolumns) {
132 # columnkeys don't contain whitespace, but some stupid tools add it
134 $csvkeycol{$keycol} = $col++;
136 #warn($borrowerline);
137 my $ext_preserve = $input->param('ext_preserve') || 0;
139 $matchpoint_attr_type = C4::Members::AttributeTypes->fetch($matchpoint);
142 push @feedback, {feedback=>1, name=>'headerrow', value=>join(', ', @csvcolumns)};
143 my $today_iso = C4::Dates->new()->output('iso');
144 my @criticals = qw(surname branchcode categorycode); # there probably should be others
145 my @bad_dates; # I've had a few.
146 my $date_re = C4::Dates->new->regexp('syspref');
147 my $iso_re = C4::Dates->new->regexp('iso');
148 LINE: while ( my $borrowerline = <$handle> ) {
150 my @missing_criticals;
151 my $patron_attributes;
152 my $status = $csv->parse($borrowerline);
153 my @columns = $csv->fields();
155 push @missing_criticals, {badparse=>1, line=>$., lineraw=>$borrowerline};
156 } elsif (@columns == @columnkeys) {
157 @borrower{@columnkeys} = @columns;
158 # MJR: try to fill blanks gracefully by using default values
159 foreach my $key (@columnkeys) {
160 if ($borrower{$key} !~ /\S/) {
161 $borrower{$key} = $defaults{$key};
165 # MJR: try to recover gracefully by using default values
166 foreach my $key (@columnkeys) {
167 if (defined($csvkeycol{$key}) and $columns[$csvkeycol{$key}] =~ /\S/) {
168 $borrower{$key} = $columns[$csvkeycol{$key}];
169 } elsif ( $defaults{$key} ) {
170 $borrower{$key} = $defaults{$key};
171 } elsif ( scalar grep {$key eq $_} @criticals ) {
172 # a critical field is undefined
173 push @missing_criticals, {key=>$key, line=>$., lineraw=>$borrowerline};
175 $borrower{$key} = '';
179 #warn join(':',%borrower);
180 if ($borrower{categorycode}) {
181 push @missing_criticals, {key=>'categorycode', line=>$. , lineraw=>$borrowerline, value=>$borrower{categorycode}, category_map=>1}
182 unless GetBorrowercategory($borrower{categorycode});
184 push @missing_criticals, {key=>'categorycode', line=>$. , lineraw=>$borrowerline};
186 if ($borrower{branchcode}) {
187 push @missing_criticals, {key=>'branchcode', line=>$. , lineraw=>$borrowerline, value=>$borrower{branchcode}, branch_map=>1}
188 unless GetBranchName($borrower{branchcode});
190 push @missing_criticals, {key=>'branchcode', line=>$. , lineraw=>$borrowerline};
192 if (@missing_criticals) {
193 foreach (@missing_criticals) {
194 $_->{borrowernumber} = $borrower{borrowernumber} || 'UNDEF';
195 $_->{surname} = $borrower{surname} || 'UNDEF';
198 (25 > scalar @errors) and push @errors, {missing_criticals=>\@missing_criticals};
199 # The first 25 errors are enough. Keeping track of 30,000+ would destroy performance.
203 my $attr_str = $borrower{patron_attributes};
204 $attr_str =~ s/\xe2\x80\x9c/"/g; # fixup double quotes in case we are passed smart quotes
205 $attr_str =~ s/\xe2\x80\x9d/"/g;
206 push @feedback, {feedback=>1, name=>'attribute string', value=>$attr_str, filename=>$uploadborrowers};
207 delete $borrower{patron_attributes}; # not really a field in borrowers, so we don't want to pass it to ModMember.
208 $patron_attributes = extended_attributes_code_value_arrayref($attr_str);
210 # Popular spreadsheet applications make it difficult to force date outputs to be zero-padded, but we require it.
211 foreach (qw(dateofbirth dateenrolled dateexpiry)) {
212 my $tempdate = $borrower{$_} or next;
213 if ($tempdate =~ /$date_re/) {
214 $borrower{$_} = format_date_in_iso($tempdate);
215 } elsif ($tempdate =~ /$iso_re/) {
216 $borrower{$_} = $tempdate;
219 push @missing_criticals, {key=>$_, line=>$. , lineraw=>$borrowerline, bad_date=>1};
222 $borrower{dateenrolled} = $today_iso unless $borrower{dateenrolled};
223 $borrower{dateexpiry} = GetExpiryDate($borrower{categorycode},$borrower{dateenrolled}) unless $borrower{dateexpiry};
226 if ( ($matchpoint eq 'cardnumber') && ($borrower{'cardnumber'}) ) {
227 $member = GetMember( 'cardnumber' => $borrower{'cardnumber'} );
229 $borrowernumber = $member->{'borrowernumber'};
231 } elsif ($extended) {
232 if (defined($matchpoint_attr_type)) {
233 foreach my $attr (@$patron_attributes) {
234 if ($attr->{code} eq $matchpoint and $attr->{value} ne '') {
235 my @borrowernumbers = $matchpoint_attr_type->get_patrons($attr->{value});
236 $borrowernumber = $borrowernumbers[0] if scalar(@borrowernumbers) == 1;
243 if ( C4::Members::checkcardnumber( $borrower{cardnumber}, $borrowernumber ) ) {
245 invalid_cardnumber => 1,
246 borrowernumber => $borrowernumber,
247 cardnumber => $borrower{cardnumber}
254 if ($borrowernumber) {
256 unless ($overwrite_cardnumber) {
258 $template->param('lastalreadyindb'=>$borrower{'surname'}.' / '.$borrowernumber);
261 $borrower{'borrowernumber'} = $borrowernumber;
262 for my $col (keys %borrower) {
263 # use values from extant patron unless our csv file includes this column or we provided a default.
264 # FIXME : You cannot update a field with a perl-evaluated false value using the defaults.
266 # The password is always encrypted, skip it!
267 next if $col eq 'password';
269 unless(exists($csvkeycol{$col}) || $defaults{$col}) {
270 $borrower{$col} = $member->{$col} if($member->{$col}) ;
273 unless (ModMember(%borrower)) {
275 # untill we have better error trapping, we have no way of knowing why ModMember errored out...
276 push @errors, {unknown_error => 1};
277 $template->param('lastinvalid'=>$borrower{'surname'}.' / '.$borrowernumber);
280 if ( $borrower{debarred} ) {
281 # Check to see if this debarment already exists
282 my $debarrments = GetDebarments(
284 borrowernumber => $borrowernumber,
285 expiration => $borrower{debarred},
286 comment => $borrower{debarredcomment}
289 # If it doesn't, then add it!
290 unless (@$debarrments) {
293 borrowernumber => $borrowernumber,
294 expiration => $borrower{debarred},
295 comment => $borrower{debarredcomment}
302 my $old_attributes = GetBorrowerAttributes($borrowernumber);
303 $patron_attributes = extended_attributes_merge($old_attributes, $patron_attributes); #TODO: expose repeatable options in template
305 push @errors, {unknown_error => 1} unless SetBorrowerAttributes($borrower{'borrowernumber'}, $patron_attributes);
308 $template->param('lastoverwritten'=>$borrower{'surname'}.' / '.$borrowernumber);
310 # FIXME: fixup_cardnumber says to lock table, but the web interface doesn't so this doesn't either.
311 # At least this is closer to AddMember than in members/memberentry.pl
312 if (!$borrower{'cardnumber'}) {
313 $borrower{'cardnumber'} = fixup_cardnumber(undef);
315 if ($borrowernumber = AddMember(%borrower)) {
317 if ( $borrower{debarred} ) {
320 borrowernumber => $borrowernumber,
321 expiration => $borrower{debarred},
322 comment => $borrower{debarredcomment}
328 SetBorrowerAttributes($borrowernumber, $patron_attributes);
331 if ($set_messaging_prefs) {
332 C4::Members::Messaging::SetMessagingPreferencesFromDefaults({ borrowernumber => $borrowernumber,
333 categorycode => $borrower{categorycode} });
337 $template->param('lastimported'=>$borrower{'surname'}.' / '.$borrowernumber);
340 push @errors, {unknown_error => 1};
341 $template->param('lastinvalid'=>$borrower{'surname'}.' / AddMember');
345 (@errors ) and $template->param( ERRORS=>\@errors );
346 (@feedback) and $template->param(FEEDBACK=>\@feedback);
348 'uploadborrowers' => 1,
349 'imported' => $imported,
350 'overwritten' => $overwritten,
351 'alreadyindb' => $alreadyindb,
352 'invalid' => $invalid,
353 'total' => $imported + $alreadyindb + $invalid + $overwritten,
358 my @matchpoints = ();
359 my @attr_types = C4::Members::AttributeTypes::GetAttributeTypes(undef, 1);
360 foreach my $type (@attr_types) {
361 my $attr_type = C4::Members::AttributeTypes->fetch($type->{code});
362 if ($attr_type->unique_id()) {
363 push @matchpoints, { code => "patron_attribute_" . $attr_type->code(), description => $attr_type->description() };
366 $template->param(matchpoints => \@matchpoints);
370 output_html_with_http_headers $input, $cookie, $template->output;