Bug 15407: Koha::Patron::Categories - replace GetBorrowercategoryList
[koha.git] / tools / import_borrowers.pl
1 #!/usr/bin/perl
2
3 # Copyright 2007 Liblime
4 # Parts copyright 2010 BibLibre
5 #
6 # This file is part of Koha.
7 #
8 # Koha is free software; you can redistribute it and/or modify it
9 # under the terms of the GNU General Public License as published by
10 # the Free Software Foundation; either version 3 of the License, or
11 # (at your option) any later version.
12 #
13 # Koha is distributed in the hope that it will be useful, but
14 # WITHOUT ANY WARRANTY; without even the implied warranty of
15 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 # GNU General Public License for more details.
17 #
18 # You should have received a copy of the GNU General Public License
19 # along with Koha; if not, see <http://www.gnu.org/licenses>.
20
21 # Script to take some borrowers data in a known format and load it into Koha
22 #
23 # File format
24 #
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
31 # gender, username, opac note, contact note, password, sort one, sort two
32 #
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
36
37 use strict;
38 use warnings;
39
40 use C4::Auth;
41 use C4::Output;
42 use C4::Context;
43 use C4::Branch qw/GetBranchesLoop GetBranchName/;
44 use C4::Members;
45 use C4::Members::Attributes qw(:all);
46 use C4::Members::AttributeTypes;
47 use C4::Members::Messaging;
48 use C4::Reports::Guided;
49 use C4::Templates;
50 use Koha::Patron::Debarments;
51 use Koha::Patrons;
52 use Koha::DateUtils;
53 use Koha::Token;
54 use Koha::Patron::Categories;
55
56 use Text::CSV;
57 # Text::CSV::Unicode, even in binary mode, fails to parse lines with these diacriticals:
58 # ė
59 # č
60
61 use CGI qw ( -utf8 );
62 # use encoding 'utf8';    # don't do this
63 use Digest::MD5 qw(md5_base64);
64
65 my (@errors, @feedback);
66 my $extended = C4::Context->preference('ExtendedPatronAttributes');
67 my $set_messaging_prefs = C4::Context->preference('EnhancedMessagingPreferences');
68 my @columnkeys = Koha::Patrons->columns();
69 @columnkeys = map { $_ ne 'borrowernumber' ? $_ : () } @columnkeys;
70 if ($extended) {
71     push @columnkeys, 'patron_attributes';
72 }
73
74 my $input = CGI->new();
75 our $csv  = Text::CSV->new({binary => 1});  # binary needed for non-ASCII Unicode
76 #push @feedback, {feedback=>1, name=>'backend', value=>$csv->backend, backend=>$csv->backend}; #XXX
77
78 my ( $template, $loggedinuser, $cookie ) = get_template_and_user({
79         template_name   => "tools/import_borrowers.tt",
80         query           => $input,
81         type            => "intranet",
82         authnotrequired => 0,
83         flagsrequired   => { tools => 'import_patrons' },
84         debug           => 1,
85 });
86
87 # get the branches and pass them to the template
88 my $branches = GetBranchesLoop();
89 $template->param( branches => $branches ) if ( $branches );
90 # get the patron categories and pass them to the template
91 my @patron_categories = Koha::Patron::Categories->search_limited({}, {order_by => ['description']});
92 $template->param( categories => \@patron_categories );
93 my $columns = C4::Templates::GetColumnDefs( $input )->{borrowers};
94 $columns = [ grep { $_->{field} ne 'borrowernumber' ? $_ : () } @$columns ];
95 $template->param( borrower_fields => $columns );
96
97 if ($input->param('sample')) {
98     print $input->header(
99         -type       => 'application/vnd.sun.xml.calc', # 'application/vnd.ms-excel' ?
100         -attachment => 'patron_import.csv',
101     );
102     $csv->combine(@columnkeys);
103     print $csv->string, "\n";
104     exit 0;
105 }
106 my $uploadborrowers = $input->param('uploadborrowers');
107 my $matchpoint      = $input->param('matchpoint');
108 if ($matchpoint) {
109     $matchpoint =~ s/^patron_attribute_//;
110 }
111 my $overwrite_cardnumber = $input->param('overwrite_cardnumber');
112
113 $template->param( SCRIPT_NAME => '/cgi-bin/koha/tools/import_borrowers.pl' );
114
115 if ( $uploadborrowers && length($uploadborrowers) > 0 ) {
116     die "Wrong CSRF token"
117         unless Koha::Token->new->check_csrf({
118             id     => C4::Context->userenv->{id},
119             secret => md5_base64( C4::Context->config('pass') ),
120             token  => scalar $input->param('csrf_token'),
121         });
122
123     push @feedback, {feedback=>1, name=>'filename', value=>$uploadborrowers, filename=>$uploadborrowers};
124     my $handle = $input->upload('uploadborrowers');
125     my $uploadinfo = $input->uploadInfo($uploadborrowers);
126     foreach (keys %$uploadinfo) {
127         push @feedback, {feedback=>1, name=>$_, value=>$uploadinfo->{$_}, $_=>$uploadinfo->{$_}};
128     }
129     my $imported    = 0;
130     my $alreadyindb = 0;
131     my $overwritten = 0;
132     my $invalid     = 0;
133     my $matchpoint_attr_type; 
134     my %defaults = $input->Vars;
135
136     # use header line to construct key to column map
137     my $borrowerline = <$handle>;
138     my $status = $csv->parse($borrowerline);
139     ($status) or push @errors, {badheader=>1,line=>$., lineraw=>$borrowerline};
140     my @csvcolumns = $csv->fields();
141     my %csvkeycol;
142     my $col = 0;
143     foreach my $keycol (@csvcolumns) {
144         # columnkeys don't contain whitespace, but some stupid tools add it
145         $keycol =~ s/ +//g;
146         $csvkeycol{$keycol} = $col++;
147     }
148     #warn($borrowerline);
149     my $ext_preserve = $input->param('ext_preserve') || 0;
150     if ($extended) {
151         $matchpoint_attr_type = C4::Members::AttributeTypes->fetch($matchpoint);
152     }
153
154     push @feedback, {feedback=>1, name=>'headerrow', value=>join(', ', @csvcolumns)};
155     my $today_iso = output_pref( { dt => dt_from_string, dateonly => 1, dateformat => 'iso' });
156     my @criticals = qw(surname branchcode categorycode);    # there probably should be others
157     my @bad_dates;  # I've had a few.
158     LINE: while ( my $borrowerline = <$handle> ) {
159         my %borrower;
160         my @missing_criticals;
161         my $patron_attributes;
162         my $status  = $csv->parse($borrowerline);
163         my @columns = $csv->fields();
164         if (! $status) {
165             push @missing_criticals, {badparse=>1, line=>$., lineraw=>$borrowerline};
166         } elsif (@columns == @columnkeys) {
167             @borrower{@columnkeys} = @columns;
168             # MJR: try to fill blanks gracefully by using default values
169             foreach my $key (@columnkeys) {
170                 if ($borrower{$key} !~ /\S/) {
171                     $borrower{$key} = $defaults{$key};
172                 }
173             } 
174         } else {
175             # MJR: try to recover gracefully by using default values
176             foreach my $key (@columnkeys) {
177                 if (defined($csvkeycol{$key}) and $columns[$csvkeycol{$key}] =~ /\S/) { 
178                     $borrower{$key} = $columns[$csvkeycol{$key}];
179                 } elsif ( $defaults{$key} ) {
180                     $borrower{$key} = $defaults{$key};
181                 } elsif ( scalar grep {$key eq $_} @criticals ) {
182                     # a critical field is undefined
183                     push @missing_criticals, {key=>$key, line=>$., lineraw=>$borrowerline};
184                 } else {
185                         $borrower{$key} = '';
186                 }
187             }
188         }
189         #warn join(':',%borrower);
190         if ($borrower{categorycode}) {
191             push @missing_criticals, {key=>'categorycode', line=>$. , lineraw=>$borrowerline, value=>$borrower{categorycode}, category_map=>1}
192                 unless Koha::Patron::Categories->find($borrower{categorycode});
193         } else {
194             push @missing_criticals, {key=>'categorycode', line=>$. , lineraw=>$borrowerline};
195         }
196         if ($borrower{branchcode}) {
197             push @missing_criticals, {key=>'branchcode', line=>$. , lineraw=>$borrowerline, value=>$borrower{branchcode}, branch_map=>1}
198                 unless GetBranchName($borrower{branchcode});
199         } else {
200             push @missing_criticals, {key=>'branchcode', line=>$. , lineraw=>$borrowerline};
201         }
202         if (@missing_criticals) {
203             foreach (@missing_criticals) {
204                 $_->{borrowernumber} = $borrower{borrowernumber} || 'UNDEF';
205                 $_->{surname}        = $borrower{surname} || 'UNDEF';
206             }
207             $invalid++;
208             (25 > scalar @errors) and push @errors, {missing_criticals=>\@missing_criticals};
209             # The first 25 errors are enough.  Keeping track of 30,000+ would destroy performance.
210             next LINE;
211         }
212         if ($extended) {
213             my $attr_str = $borrower{patron_attributes};
214             $attr_str =~ s/\xe2\x80\x9c/"/g; # fixup double quotes in case we are passed smart quotes
215             $attr_str =~ s/\xe2\x80\x9d/"/g;
216             push @feedback, {feedback=>1, name=>'attribute string', value=>$attr_str, filename=>$uploadborrowers};
217             delete $borrower{patron_attributes};    # not really a field in borrowers, so we don't want to pass it to ModMember.
218             $patron_attributes = extended_attributes_code_value_arrayref($attr_str); 
219         }
220         # Popular spreadsheet applications make it difficult to force date outputs to be zero-padded, but we require it.
221         foreach (qw(dateofbirth dateenrolled dateexpiry)) {
222             my $tempdate = $borrower{$_} or next;
223             $tempdate = eval { output_pref( { dt => dt_from_string( $tempdate ), dateonly => 1, dateformat => 'iso' } ); };
224             if ($tempdate) {
225                 $borrower{$_} = $tempdate;
226             } else {
227                 $borrower{$_} = '';
228                 push @missing_criticals, {key=>$_, line=>$. , lineraw=>$borrowerline, bad_date=>1};
229             }
230         }
231         $borrower{dateenrolled} = $today_iso unless $borrower{dateenrolled};
232         $borrower{dateexpiry} = GetExpiryDate($borrower{categorycode},$borrower{dateenrolled}) unless $borrower{dateexpiry}; 
233         my $borrowernumber;
234         my $member;
235         if ( ($matchpoint eq 'cardnumber') && ($borrower{'cardnumber'}) ) {
236             $member = GetMember( 'cardnumber' => $borrower{'cardnumber'} );
237             if ($member) {
238                 $borrowernumber = $member->{'borrowernumber'};
239             }
240         } elsif ( ($matchpoint eq 'userid') && ($borrower{'userid'}) ) {
241             $member = GetMember( 'userid' => $borrower{'userid'} );
242             if ($member) {
243                 $borrowernumber = $member->{'borrowernumber'};
244             }
245         } elsif ($extended) {
246             if (defined($matchpoint_attr_type)) {
247                 foreach my $attr (@$patron_attributes) {
248                     if ($attr->{code} eq $matchpoint and $attr->{value} ne '') {
249                         my @borrowernumbers = $matchpoint_attr_type->get_patrons($attr->{value});
250                         $borrowernumber = $borrowernumbers[0] if scalar(@borrowernumbers) == 1;
251                         last;
252                     }
253                 }
254             }
255         }
256
257         if ( C4::Members::checkcardnumber( $borrower{cardnumber}, $borrowernumber ) ) {
258             push @errors, {
259                 invalid_cardnumber => 1,
260                 borrowernumber => $borrowernumber,
261                 cardnumber => $borrower{cardnumber}
262             };
263             $invalid++;
264             next;
265         }
266
267         if ($borrowernumber) {
268             # borrower exists
269             unless ($overwrite_cardnumber) {
270                 $alreadyindb++;
271                 $template->param('lastalreadyindb'=>$borrower{'surname'}.' / '.$borrowernumber);
272                 next LINE;
273             }
274             $borrower{'borrowernumber'} = $borrowernumber;
275             for my $col (keys %borrower) {
276                 # use values from extant patron unless our csv file includes this column or we provided a default.
277                 # FIXME : You cannot update a field with a  perl-evaluated false value using the defaults.
278
279                 # The password is always encrypted, skip it!
280                 next if $col eq 'password';
281
282                 unless(exists($csvkeycol{$col}) || $defaults{$col}) {
283                     $borrower{$col} = $member->{$col} if($member->{$col}) ;
284                 }
285             }
286
287             # Check if the userid provided does not exist yet
288             if (  exists $borrower{userid}
289                      and $borrower{userid}
290                  and not Check_Userid( $borrower{userid}, $borrower{borrowernumber} ) ) {
291                 push @errors, { duplicate_userid => 1, userid => $borrower{userid} };
292                 $invalid++;
293                 next LINE;
294             }
295
296             unless (ModMember(%borrower)) {
297                 $invalid++;
298                 # until we have better error trapping, we have no way of knowing why ModMember errored out...
299                 push @errors, {unknown_error => 1};
300                 $template->param('lastinvalid'=>$borrower{'surname'}.' / '.$borrowernumber);
301                 next LINE;
302             }
303
304             # Don't add a new restriction if the existing 'combined' restriction matches this one
305             if ( $borrower{debarred} && ( ( $borrower{debarred} ne $member->{debarred} ) || ( $borrower{debarredcomment} ne $member->{debarredcomment} ) ) ) {
306                 # Check to see if this debarment already exists
307                 my $debarrments = GetDebarments(
308                     {
309                         borrowernumber => $borrowernumber,
310                         expiration     => $borrower{debarred},
311                         comment        => $borrower{debarredcomment}
312                     }
313                 );
314                 # If it doesn't, then add it!
315                 unless (@$debarrments) {
316                     AddDebarment(
317                         {
318                             borrowernumber => $borrowernumber,
319                             expiration     => $borrower{debarred},
320                             comment        => $borrower{debarredcomment}
321                         }
322                     );
323                 }
324             }
325
326             if ($extended) {
327                 if ($ext_preserve) {
328                     my $old_attributes = GetBorrowerAttributes($borrowernumber);
329                     $patron_attributes = extended_attributes_merge($old_attributes, $patron_attributes);  #TODO: expose repeatable options in template
330                 }
331                 push @errors, {unknown_error => 1} unless SetBorrowerAttributes($borrower{'borrowernumber'}, $patron_attributes, 'no_branch_limit' );
332             }
333             $overwritten++;
334             $template->param('lastoverwritten'=>$borrower{'surname'}.' / '.$borrowernumber);
335         } else {
336             # FIXME: fixup_cardnumber says to lock table, but the web interface doesn't so this doesn't either.
337             # At least this is closer to AddMember than in members/memberentry.pl
338             if (!$borrower{'cardnumber'}) {
339                 $borrower{'cardnumber'} = fixup_cardnumber(undef);
340             }
341             if ($borrowernumber = AddMember(%borrower)) {
342
343                 if ( $borrower{debarred} ) {
344                     AddDebarment(
345                         {
346                             borrowernumber => $borrowernumber,
347                             expiration     => $borrower{debarred},
348                             comment        => $borrower{debarredcomment}
349                         }
350                     );
351                 }
352
353                 if ($extended) {
354                     SetBorrowerAttributes($borrowernumber, $patron_attributes);
355                 }
356
357                 if ($set_messaging_prefs) {
358                     C4::Members::Messaging::SetMessagingPreferencesFromDefaults({ borrowernumber => $borrowernumber,
359                                                                                   categorycode => $borrower{categorycode} });
360                 }
361
362                 $imported++;
363                 $template->param('lastimported'=>$borrower{'surname'}.' / '.$borrowernumber);
364             } else {
365                 $invalid++;
366                 push @errors, {unknown_error => 1};
367                 $template->param('lastinvalid'=>$borrower{'surname'}.' / AddMember');
368             }
369         }
370     }
371     (@errors  ) and $template->param(  ERRORS=>\@errors  );
372     (@feedback) and $template->param(FEEDBACK=>\@feedback);
373     $template->param(
374         'uploadborrowers' => 1,
375         'imported'        => $imported,
376         'overwritten'     => $overwritten,
377         'alreadyindb'     => $alreadyindb,
378         'invalid'         => $invalid,
379         'total'           => $imported + $alreadyindb + $invalid + $overwritten,
380     );
381
382 } else {
383     if ($extended) {
384         my @matchpoints = ();
385         my @attr_types = C4::Members::AttributeTypes::GetAttributeTypes(undef, 1);
386         foreach my $type (@attr_types) {
387             my $attr_type = C4::Members::AttributeTypes->fetch($type->{code});
388             if ($attr_type->unique_id()) {
389             push @matchpoints, { code =>  "patron_attribute_" . $attr_type->code(), description => $attr_type->description() };
390             }
391         }
392         $template->param(matchpoints => \@matchpoints);
393     }
394
395     $template->param(
396         csrf_token => Koha::Token->new->generate_csrf(
397             {   id     => C4::Context->userenv->{id},
398                 secret => md5_base64( C4::Context->config('pass') ),
399             }
400         ),
401     );
402
403 }
404
405 output_html_with_http_headers $input, $cookie, $template->output;
406