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;
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 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};
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);
129 $matchpoint_attr_type = C4::Members::AttributeTypes->fetch($matchpoint);
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> ) {
140 my @missing_criticals;
141 my $patron_attributes;
142 my $status = $csv->parse($borrowerline);
143 my @columns = $csv->fields();
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};
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};
165 $borrower{$key} = '';
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});
174 push @missing_criticals, {key=>'categorycode', line=>$. , lineraw=>$borrowerline};
176 if ($borrower{branchcode}) {
177 push @missing_criticals, {key=>'branchcode', line=>$. , lineraw=>$borrowerline, value=>$borrower{branchcode}, branch_map=>1}
178 unless GetBranchName($borrower{branchcode});
180 push @missing_criticals, {key=>'branchcode', line=>$. , lineraw=>$borrowerline};
182 if (@missing_criticals) {
183 foreach (@missing_criticals) {
184 $_->{borrowernumber} = $borrower{borrowernumber} || 'UNDEF';
185 $_->{surname} = $borrower{surname} || 'UNDEF';
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.
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 ];
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;
210 push @missing_criticals, {key=>$_, line=>$. , lineraw=>$borrowerline, bad_date=>1};
213 $borrower{dateenrolled} = $today_iso unless $borrower{dateenrolled};
214 $borrower{dateexpiry} = GetExpiryDate($borrower{categorycode},$borrower{dateenrolled}) unless $borrower{dateexpiry};
217 if ( ($matchpoint eq 'cardnumber') && ($borrower{'cardnumber'}) ) {
218 $member = GetMember( $borrower{'cardnumber'}, 'cardnumber' );
220 $borrowernumber = $member->{'borrowernumber'};
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;
234 if ($borrowernumber) {
236 unless ($overwrite_cardnumber) {
238 $template->param('lastalreadyindb'=>$borrower{'surname'}.' / '.$borrowernumber);
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}) ;
249 unless (ModMember(%borrower)) {
251 $template->param('lastinvalid'=>$borrower{'surname'}.' / '.$borrowernumber);
255 C4::Members::Attributes::SetBorrowerAttributes($borrower{'borrowernumber'}, $patron_attributes);
258 $template->param('lastoverwritten'=>$borrower{'surname'}.' / '.$borrowernumber);
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);
265 if ($borrowernumber = AddMember(%borrower)) {
267 C4::Members::Attributes::SetBorrowerAttributes($borrowernumber, $patron_attributes);
269 if ($set_messaging_prefs) {
270 C4::Members::Messaging::SetMessagingPreferencesFromDefaults({ borrowernumber => $borrowernumber,
271 categorycode => $borrower{categorycode} });
274 $template->param('lastimported'=>$borrower{'surname'}.' / '.$borrowernumber);
276 $invalid++; # was just "$invalid", I assume incrementing was the point --atz
277 $template->param('lastinvalid'=>$borrower{'surname'}.' / AddMember');
281 (@errors ) and $template->param( ERRORS=>\@errors );
282 (@feedback) and $template->param(FEEDBACK=>\@feedback);
284 'uploadborrowers' => 1,
285 'imported' => $imported,
286 'overwritten' => $overwritten,
287 'alreadyindb' => $alreadyindb,
288 'invalid' => $invalid,
289 'total' => $imported + $alreadyindb + $invalid + $overwritten,
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() };
302 $template->param(matchpoints => \@matchpoints);
306 output_html_with_http_headers $input, $cookie, $template->output;