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
39 use C4::Dates qw(format_date_in_iso);
41 use C4::Branch qw(GetBranchName);
43 use C4::Members::Attributes;
44 use C4::Members::AttributeTypes;
50 my $extended = C4::Context->preference('ExtendedPatronAttributes');
51 my @columnkeys = C4::Members->columns;
53 push @columnkeys, 'patron_attributes';
55 my $columnkeystpl = [ map { {'key' => $_} } grep {$_ ne 'borrowernumber' && $_ ne 'cardnumber'} @columnkeys ]; # ref. to array of hashrefs.
57 my $input = CGI->new();
58 my $csv = Text::CSV->new();
60 my ( $template, $loggedinuser, $cookie ) = get_template_and_user({
61 template_name => "tools/import_borrowers.tmpl",
65 flagsrequired => { tools => 'import_patrons' },
69 $template->param(columnkeys => $columnkeystpl);
71 if ($input->param('sample')) {
73 -type => 'application/vnd.sun.xml.calc', # 'application/vnd.ms-excel' ?
74 -attachment => 'patron_import.csv',
76 $csv->combine(@columnkeys);
77 print $csv->string, "\n";
80 my $uploadborrowers = $input->param('uploadborrowers');
81 my $matchpoint = $input->param('matchpoint');
83 $matchpoint =~ s/^patron_attribute_//;
85 my $overwrite_cardnumber = $input->param('overwrite_cardnumber');
87 $template->param( SCRIPT_NAME => $ENV{'SCRIPT_NAME'} );
89 ($extended) and $template->param(ExtendedPatronAttributes => 1);
91 if ( $uploadborrowers && length($uploadborrowers) > 0 ) {
96 my $matchpoint_attr_type;
97 my %defaults = $input->Vars;
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();
106 foreach my $keycol (@csvcolumns) {
107 # columnkeys don't contain whitespace, but some stupid tools add it
109 $csvkeycol{$keycol} = $col++;
111 #warn($borrowerline);
113 $matchpoint_attr_type = C4::Members::AttributeTypes->fetch($matchpoint);
116 my @criticals = qw(cardnumber surname categorycode); # there probably should be others
118 LINE: while ( my $borrowerline = <$uploadborrowers> ) {
120 my @missing_criticals;
121 my $patron_attributes;
122 my $status = $csv->parse($borrowerline);
123 my @columns = $csv->fields();
125 push @missing_criticals, {badparse=>1, line=>$., lineraw=>$borrowerline};
126 } elsif (@columns == @columnkeys) {
127 @borrower{@columnkeys} = @columns;
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};
139 $borrower{$key} = '';
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';
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.
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 ];
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) || '';
170 $borrower{dateenrolled} = C4::Dates->new()->output('iso') unless $borrower{dateenrolled};
171 $borrower{dateexpiry} = GetExpiryDate($borrower{categorycode},$borrower{dateenrolled}) unless $borrower{dateexpiry};
174 if ($matchpoint eq 'cardnumber') {
175 $member = GetMember( $borrower{'cardnumber'}, 'cardnumber' );
177 $borrowernumber = $member->{'borrowernumber'};
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;
191 if ($borrowernumber) {
193 unless ($overwrite_cardnumber) {
195 $template->param('lastalreadyindb'=>$borrower{'surname'}.' / '.$borrowernumber);
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}) ;
206 unless (ModMember(%borrower)) {
208 $template->param('lastinvalid'=>$borrower{'surname'}.' / '.$borrowernumber);
212 C4::Members::Attributes::SetBorrowerAttributes($borrower{'borrowernumber'}, $patron_attributes);
215 $template->param('lastoverwritten'=>$borrower{'surname'}.' / '.$borrowernumber);
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('');
222 if ($borrowernumber = AddMember(%borrower)) {
224 C4::Members::Attributes::SetBorrowerAttributes($borrowernumber, $patron_attributes);
227 $template->param('lastimported'=>$borrower{'surname'}.' / '.$borrowernumber);
229 $invalid++; # was just "$invalid", I assume incrementing was the point --atz
230 $template->param('lastinvalid'=>$borrower{'surname'}.' / AddMember');
234 (@errors) and $template->param(ERRORS=>\@errors);
236 'uploadborrowers' => 1,
237 'imported' => $imported,
238 'overwritten' => $overwritten,
239 'alreadyindb' => $alreadyindb,
240 'invalid' => $invalid,
241 'total' => $imported + $alreadyindb + $invalid + $overwritten,
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() };
254 $template->param(matchpoints => \@matchpoints);
258 output_html_with_http_headers $input, $cookie, $template->output;