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 with
17 # Koha; if not, write to the Free Software Foundation, Inc., 59 Temple Place,
18 # Suite 330, Boston, MA 02111-1307 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, 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
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;
49 # Text::CSV::Unicode, even in binary mode, fails to parse lines with these diacriticals:
54 # use encoding 'utf8'; # don't do this
56 my (@errors, @feedback);
57 my $extended = C4::Context->preference('ExtendedPatronAttributes');
58 my @columnkeys = C4::Members->columns;
60 push @columnkeys, 'patron_attributes';
62 my $columnkeystpl = [ map { {'key' => $_} } grep {$_ ne 'borrowernumber' && $_ ne 'cardnumber'} @columnkeys ]; # ref. to array of hashrefs.
64 my $input = CGI->new();
65 our $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};
68 my ( $template, $loggedinuser, $cookie ) = get_template_and_user({
69 template_name => "tools/import_borrowers.tmpl",
73 flagsrequired => { tools => 'import_patrons' },
77 $template->param(columnkeys => $columnkeystpl);
79 if ($input->param('sample')) {
81 -type => 'application/vnd.sun.xml.calc', # 'application/vnd.ms-excel' ?
82 -attachment => 'patron_import.csv',
84 $csv->combine(@columnkeys);
85 print $csv->string, "\n";
88 my $uploadborrowers = $input->param('uploadborrowers');
89 my $matchpoint = $input->param('matchpoint');
91 $matchpoint =~ s/^patron_attribute_//;
93 my $overwrite_cardnumber = $input->param('overwrite_cardnumber');
95 $template->param( SCRIPT_NAME => $ENV{'SCRIPT_NAME'} );
97 ($extended) and $template->param(ExtendedPatronAttributes => 1);
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->{$_}};
110 my $matchpoint_attr_type;
111 my %defaults = $input->Vars;
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();
120 foreach my $keycol (@csvcolumns) {
121 # columnkeys don't contain whitespace, but some stupid tools add it
123 $csvkeycol{$keycol} = $col++;
125 #warn($borrowerline);
126 my $ext_preserve = $input->param('ext_preserve') || 0;
128 $matchpoint_attr_type = C4::Members::AttributeTypes->fetch($matchpoint);
131 push @feedback, {feedback=>1, name=>'headerrow', value=>join(', ', @csvcolumns)};
132 my $today_iso = C4::Dates->new()->output('iso');
133 my @criticals = qw(surname branchcode categorycode); # there probably should be others
134 my @bad_dates; # I've had a few.
135 my $date_re = C4::Dates->new->regexp('syspref');
136 my $iso_re = C4::Dates->new->regexp('iso');
137 LINE: while ( my $borrowerline = <$handle> ) {
139 my @missing_criticals;
140 my $patron_attributes;
141 my $status = $csv->parse($borrowerline);
142 my @columns = $csv->fields();
144 push @missing_criticals, {badparse=>1, line=>$., lineraw=>$borrowerline};
145 } elsif (@columns == @columnkeys) {
146 @borrower{@columnkeys} = @columns;
147 # MJR: try to fill blanks gracefully by using default values
148 foreach my $key (@criticals) {
149 if ($borrower{$key} !~ /\S/) {
150 $borrower{$key} = $defaults{$key};
154 # MJR: try to recover gracefully by using default values
155 foreach my $key (@columnkeys) {
156 if (defined($csvkeycol{$key}) and $columns[$csvkeycol{$key}] =~ /\S/) {
157 $borrower{$key} = $columns[$csvkeycol{$key}];
158 } elsif ( $defaults{$key} ) {
159 $borrower{$key} = $defaults{$key};
160 } elsif ( scalar grep {$key eq $_} @criticals ) {
161 # a critical field is undefined
162 push @missing_criticals, {key=>$key, line=>$., lineraw=>$borrowerline};
164 $borrower{$key} = '';
168 #warn join(':',%borrower);
169 if ($borrower{categorycode}) {
170 push @missing_criticals, {key=>'categorycode', line=>$. , lineraw=>$borrowerline, value=>$borrower{categorycode}, category_map=>1}
171 unless GetBorrowercategory($borrower{categorycode});
173 push @missing_criticals, {key=>'categorycode', line=>$. , lineraw=>$borrowerline};
175 if ($borrower{branchcode}) {
176 push @missing_criticals, {key=>'branchcode', line=>$. , lineraw=>$borrowerline, value=>$borrower{branchcode}, branch_map=>1}
177 unless GetBranchName($borrower{branchcode});
179 push @missing_criticals, {key=>'branchcode', line=>$. , lineraw=>$borrowerline};
181 if (@missing_criticals) {
182 foreach (@missing_criticals) {
183 $_->{borrowernumber} = $borrower{borrowernumber} || 'UNDEF';
184 $_->{surname} = $borrower{surname} || 'UNDEF';
187 (25 > scalar @errors) and push @errors, {missing_criticals=>\@missing_criticals};
188 # The first 25 errors are enough. Keeping track of 30,000+ would destroy performance.
192 my $attr_str = $borrower{patron_attributes};
193 delete $borrower{patron_attributes}; # not really a field in borrowers, so we don't want to pass it to ModMember.
194 $patron_attributes = extended_attributes_code_value_arrayref($attr_str);
196 # Popular spreadsheet applications make it difficult to force date outputs to be zero-padded, but we require it.
197 foreach (qw(dateofbirth dateenrolled dateexpiry)) {
198 my $tempdate = $borrower{$_} or next;
199 if ($tempdate =~ /$date_re/) {
200 $borrower{$_} = format_date_in_iso($tempdate);
201 } elsif ($tempdate =~ /$iso_re/) {
202 $borrower{$_} = $tempdate;
205 push @missing_criticals, {key=>$_, line=>$. , lineraw=>$borrowerline, bad_date=>1};
208 $borrower{dateenrolled} = $today_iso unless $borrower{dateenrolled};
209 $borrower{dateexpiry} = GetExpiryDate($borrower{categorycode},$borrower{dateenrolled}) unless $borrower{dateexpiry};
212 if ( ($matchpoint eq 'cardnumber') && ($borrower{'cardnumber'}) ) {
213 $member = GetMember( $borrower{'cardnumber'}, 'cardnumber' );
215 $borrowernumber = $member->{'borrowernumber'};
217 } elsif ($extended) {
218 if (defined($matchpoint_attr_type)) {
219 foreach my $attr (@$patron_attributes) {
220 if ($attr->{code} eq $matchpoint and $attr->{value} ne '') {
221 my @borrowernumbers = $matchpoint_attr_type->get_patrons($attr->{value});
222 $borrowernumber = $borrowernumbers[0] if scalar(@borrowernumbers) == 1;
229 if ($borrowernumber) {
231 unless ($overwrite_cardnumber) {
233 $template->param('lastalreadyindb'=>$borrower{'surname'}.' / '.$borrowernumber);
236 $borrower{'borrowernumber'} = $borrowernumber;
237 for my $col (keys %borrower) {
238 # use values from extant patron unless our csv file includes this column or we provided a default.
239 # FIXME : You cannot update a field with a perl-evaluated false value using the defaults.
240 unless(exists($csvkeycol{$col}) || $defaults{$col}) {
241 $borrower{$col} = $member->{$col} if($member->{$col}) ;
244 unless (ModMember(%borrower)) {
246 $template->param('lastinvalid'=>$borrower{'surname'}.' / '.$borrowernumber);
251 my $old_attributes = GetBorrowerAttributes($borrowernumber);
252 $patron_attributes = extended_attributes_merge($old_attributes, $patron_attributes); #TODO: expose repeatable options in template
254 SetBorrowerAttributes($borrower{'borrowernumber'}, $patron_attributes);
257 $template->param('lastoverwritten'=>$borrower{'surname'}.' / '.$borrowernumber);
259 # FIXME: fixup_cardnumber says to lock table, but the web interface doesn't so this doesn't either.
260 # At least this is closer to AddMember than in members/memberentry.pl
261 if (!$borrower{'cardnumber'}) {
262 $borrower{'cardnumber'} = fixup_cardnumber(undef);
264 if ($borrowernumber = AddMember(%borrower)) {
266 SetBorrowerAttributes($borrowernumber, $patron_attributes);
269 $template->param('lastimported'=>$borrower{'surname'}.' / '.$borrowernumber);
272 $template->param('lastinvalid'=>$borrower{'surname'}.' / AddMember');
276 (@errors ) and $template->param( ERRORS=>\@errors );
277 (@feedback) and $template->param(FEEDBACK=>\@feedback);
279 'uploadborrowers' => 1,
280 'imported' => $imported,
281 'overwritten' => $overwritten,
282 'alreadyindb' => $alreadyindb,
283 'invalid' => $invalid,
284 'total' => $imported + $alreadyindb + $invalid + $overwritten,
289 my @matchpoints = ();
290 my @attr_types = C4::Members::AttributeTypes::GetAttributeTypes();
291 foreach my $type (@attr_types) {
292 my $attr_type = C4::Members::AttributeTypes->fetch($type->{code});
293 if ($attr_type->unique_id()) {
294 push @matchpoints, { code => "patron_attribute_" . $attr_type->code(), description => $attr_type->description() };
297 $template->param(matchpoints => \@matchpoints);
301 output_html_with_http_headers $input, $cookie, $template->output;