3 # Copyright 2007 Liblime Ltd
5 # This file is part of Koha.
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
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.
16 # You should have received a copy of the GNU General Public License along
17 # with Koha; if not, write to the Free Software Foundation, Inc.,
18 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
20 # Script to take some borrowers data in a known format and load it into Koha
24 # cardnumber,surname,firstname,title,othernames,initials,streetnumber,streettype,
25 # address line , address line 2, city, zipcode, contry, email, phone, mobile, fax, work email, work phone,
26 # alternate streetnumber, alternate streettype, alternate address line 1, alternate city,
27 # alternate zipcode, alternate country, 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
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
41 use C4
::Dates
qw(format_date_in_iso);
43 use C4
::Branch
qw(GetBranchName);
45 use C4
::Members
::Attributes
qw(:all);
46 use C4
::Members
::AttributeTypes
;
47 use C4
::Members
::Messaging
;
50 # Text::CSV::Unicode, even in binary mode, fails to parse lines with these diacriticals:
55 # use encoding 'utf8'; # don't do this
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;
62 push @columnkeys, 'patron_attributes';
64 my $columnkeystpl = [ map { {'key' => $_} } grep {$_ ne 'borrowernumber' && $_ ne 'cardnumber'} @columnkeys ]; # ref. to array of hashrefs.
66 my $input = CGI
->new();
67 our $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};
70 my ( $template, $loggedinuser, $cookie ) = get_template_and_user
({
71 template_name
=> "tools/import_borrowers.tmpl",
75 flagsrequired
=> { tools
=> 'import_patrons' },
79 $template->param(columnkeys
=> $columnkeystpl);
81 if ($input->param('sample')) {
83 -type
=> 'application/vnd.sun.xml.calc', # 'application/vnd.ms-excel' ?
84 -attachment
=> 'patron_import.csv',
86 $csv->combine(@columnkeys);
87 print $csv->string, "\n";
90 my $uploadborrowers = $input->param('uploadborrowers');
91 my $matchpoint = $input->param('matchpoint');
93 $matchpoint =~ s/^patron_attribute_//;
95 my $overwrite_cardnumber = $input->param('overwrite_cardnumber');
97 $template->param( SCRIPT_NAME
=> $ENV{'SCRIPT_NAME'} );
99 ($extended) and $template->param(ExtendedPatronAttributes
=> 1);
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->{$_}};
112 my $matchpoint_attr_type;
113 my %defaults = $input->Vars;
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();
122 foreach my $keycol (@csvcolumns) {
123 # columnkeys don't contain whitespace, but some stupid tools add it
125 $csvkeycol{$keycol} = $col++;
127 #warn($borrowerline);
128 my $ext_preserve = $input->param('ext_preserve') || 0;
130 $matchpoint_attr_type = C4
::Members
::AttributeTypes
->fetch($matchpoint);
133 push @feedback, {feedback
=>1, name
=>'headerrow', value
=>join(', ', @csvcolumns)};
134 my $today_iso = C4
::Dates
->new()->output('iso');
135 my @criticals = qw(surname branchcode categorycode); # there probably should be others
136 my @bad_dates; # I've had a few.
137 my $date_re = C4
::Dates
->new->regexp('syspref');
138 my $iso_re = C4
::Dates
->new->regexp('iso');
139 LINE
: while ( my $borrowerline = <$handle> ) {
141 my @missing_criticals;
142 my $patron_attributes;
143 my $status = $csv->parse($borrowerline);
144 my @columns = $csv->fields();
146 push @missing_criticals, {badparse
=>1, line
=>$., lineraw
=>$borrowerline};
147 } elsif (@columns == @columnkeys) {
148 @borrower{@columnkeys} = @columns;
149 # MJR: try to fill blanks gracefully by using default values
150 foreach my $key (@criticals) {
151 if ($borrower{$key} !~ /\S/) {
152 $borrower{$key} = $defaults{$key};
156 # MJR: try to recover gracefully by using default values
157 foreach my $key (@columnkeys) {
158 if (defined($csvkeycol{$key}) and $columns[$csvkeycol{$key}] =~ /\S/) {
159 $borrower{$key} = $columns[$csvkeycol{$key}];
160 } elsif ( $defaults{$key} ) {
161 $borrower{$key} = $defaults{$key};
162 } elsif ( scalar grep {$key eq $_} @criticals ) {
163 # a critical field is undefined
164 push @missing_criticals, {key
=>$key, line
=>$., lineraw
=>$borrowerline};
166 $borrower{$key} = '';
170 #warn join(':',%borrower);
171 if ($borrower{categorycode
}) {
172 push @missing_criticals, {key
=>'categorycode', line
=>$. , lineraw
=>$borrowerline, value
=>$borrower{categorycode
}, category_map
=>1}
173 unless GetBorrowercategory
($borrower{categorycode
});
175 push @missing_criticals, {key
=>'categorycode', line
=>$. , lineraw
=>$borrowerline};
177 if ($borrower{branchcode
}) {
178 push @missing_criticals, {key
=>'branchcode', line
=>$. , lineraw
=>$borrowerline, value
=>$borrower{branchcode
}, branch_map
=>1}
179 unless GetBranchName
($borrower{branchcode
});
181 push @missing_criticals, {key
=>'branchcode', line
=>$. , lineraw
=>$borrowerline};
183 if (@missing_criticals) {
184 foreach (@missing_criticals) {
185 $_->{borrowernumber
} = $borrower{borrowernumber
} || 'UNDEF';
186 $_->{surname
} = $borrower{surname
} || 'UNDEF';
189 (25 > scalar @errors) and push @errors, {missing_criticals
=>\
@missing_criticals};
190 # The first 25 errors are enough. Keeping track of 30,000+ would destroy performance.
194 my $attr_str = $borrower{patron_attributes
};
195 delete $borrower{patron_attributes
}; # not really a field in borrowers, so we don't want to pass it to ModMember.
196 $patron_attributes = extended_attributes_code_value_arrayref
($attr_str);
198 # Popular spreadsheet applications make it difficult to force date outputs to be zero-padded, but we require it.
199 foreach (qw(dateofbirth dateenrolled dateexpiry)) {
200 my $tempdate = $borrower{$_} or next;
201 if ($tempdate =~ /$date_re/) {
202 $borrower{$_} = format_date_in_iso
($tempdate);
203 } elsif ($tempdate =~ /$iso_re/) {
204 $borrower{$_} = $tempdate;
207 push @missing_criticals, {key
=>$_, line
=>$. , lineraw
=>$borrowerline, bad_date
=>1};
210 $borrower{dateenrolled
} = $today_iso unless $borrower{dateenrolled
};
211 $borrower{dateexpiry
} = GetExpiryDate
($borrower{categorycode
},$borrower{dateenrolled
}) unless $borrower{dateexpiry
};
214 if ( ($matchpoint eq 'cardnumber') && ($borrower{'cardnumber'}) ) {
215 $member = GetMember
( 'cardnumber' => $borrower{'cardnumber'} );
217 $borrowernumber = $member->{'borrowernumber'};
219 } elsif ($extended) {
220 if (defined($matchpoint_attr_type)) {
221 foreach my $attr (@
$patron_attributes) {
222 if ($attr->{code
} eq $matchpoint and $attr->{value
} ne '') {
223 my @borrowernumbers = $matchpoint_attr_type->get_patrons($attr->{value
});
224 $borrowernumber = $borrowernumbers[0] if scalar(@borrowernumbers) == 1;
231 if ($borrowernumber) {
233 unless ($overwrite_cardnumber) {
235 $template->param('lastalreadyindb'=>$borrower{'surname'}.' / '.$borrowernumber);
238 $borrower{'borrowernumber'} = $borrowernumber;
239 for my $col (keys %borrower) {
240 # use values from extant patron unless our csv file includes this column or we provided a default.
241 # FIXME : You cannot update a field with a perl-evaluated false value using the defaults.
242 unless(exists($csvkeycol{$col}) || $defaults{$col}) {
243 $borrower{$col} = $member->{$col} if($member->{$col}) ;
246 unless (ModMember
(%borrower)) {
248 $template->param('lastinvalid'=>$borrower{'surname'}.' / '.$borrowernumber);
253 my $old_attributes = GetBorrowerAttributes
($borrowernumber);
254 $patron_attributes = extended_attributes_merge
($old_attributes, $patron_attributes); #TODO: expose repeatable options in template
256 SetBorrowerAttributes
($borrower{'borrowernumber'}, $patron_attributes);
259 $template->param('lastoverwritten'=>$borrower{'surname'}.' / '.$borrowernumber);
261 # FIXME: fixup_cardnumber says to lock table, but the web interface doesn't so this doesn't either.
262 # At least this is closer to AddMember than in members/memberentry.pl
263 if (!$borrower{'cardnumber'}) {
264 $borrower{'cardnumber'} = fixup_cardnumber
(undef);
266 if ($borrowernumber = AddMember
(%borrower)) {
268 SetBorrowerAttributes
($borrowernumber, $patron_attributes);
270 if ($set_messaging_prefs) {
271 C4
::Members
::Messaging
::SetMessagingPreferencesFromDefaults
({ borrowernumber
=> $borrowernumber,
272 categorycode
=> $borrower{categorycode
} });
275 $template->param('lastimported'=>$borrower{'surname'}.' / '.$borrowernumber);
278 $template->param('lastinvalid'=>$borrower{'surname'}.' / AddMember');
282 (@errors ) and $template->param( ERRORS
=>\
@errors );
283 (@feedback) and $template->param(FEEDBACK
=>\
@feedback);
285 'uploadborrowers' => 1,
286 'imported' => $imported,
287 'overwritten' => $overwritten,
288 'alreadyindb' => $alreadyindb,
289 'invalid' => $invalid,
290 'total' => $imported + $alreadyindb + $invalid + $overwritten,
295 my @matchpoints = ();
296 my @attr_types = C4
::Members
::AttributeTypes
::GetAttributeTypes
();
297 foreach my $type (@attr_types) {
298 my $attr_type = C4
::Members
::AttributeTypes
->fetch($type->{code
});
299 if ($attr_type->unique_id()) {
300 push @matchpoints, { code
=> "patron_attribute_" . $attr_type->code(), description
=> $attr_type->description() };
303 $template->param(matchpoints
=> \
@matchpoints);
307 output_html_with_http_headers
$input, $cookie, $template->output;