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