Bug 12598: New misc/import_borrowers.pl command line tool
[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 Modern::Perl;
38
39 use C4::Auth;
40 use C4::Output;
41 use C4::Templates;
42 use Koha::Patron::Debarments;
43 use Koha::Patrons;
44 use Koha::DateUtils;
45 use Koha::Token;
46 use Koha::Libraries;
47 use Koha::Patron::Categories;
48 use Koha::List::Patron;
49
50 use Koha::Patrons::Import;
51 my $Import = Koha::Patrons::Import->new();
52
53 use Text::CSV;
54
55 # Text::CSV::Unicode, even in binary mode, fails to parse lines with these diacriticals:
56 # ė
57 # č
58
59 use CGI qw ( -utf8 );
60
61 my ( @errors, @feedback );
62 my $extended = C4::Context->preference('ExtendedPatronAttributes');
63
64 my @columnkeys = map { $_ ne 'borrowernumber' ? $_ : () } Koha::Patrons->columns();
65 push( @columnkeys, 'patron_attributes' ) if $extended;
66
67 my $input = CGI->new();
68
69 #push @feedback, {feedback=>1, name=>'backend', value=>$csv->backend, backend=>$csv->backend}; #XXX
70
71 my ( $template, $loggedinuser, $cookie ) = get_template_and_user(
72     {
73         template_name   => "tools/import_borrowers.tt",
74         query           => $input,
75         type            => "intranet",
76         authnotrequired => 0,
77         flagsrequired   => { tools => 'import_patrons' },
78         debug           => 1,
79     }
80 );
81
82 # get the patron categories and pass them to the template
83 my @patron_categories = Koha::Patron::Categories->search_limited({}, {order_by => ['description']});
84 $template->param( categories => \@patron_categories );
85 my $columns = C4::Templates::GetColumnDefs( $input )->{borrowers};
86 $columns = [ grep { $_->{field} ne 'borrowernumber' ? $_ : () } @$columns ];
87 $template->param( borrower_fields => $columns );
88
89 if ( $input->param('sample') ) {
90     our $csv = Text::CSV->new( { binary => 1 } );    # binary needed for non-ASCII Unicode
91     print $input->header(
92         -type       => 'application/vnd.sun.xml.calc',    # 'application/vnd.ms-excel' ?
93         -attachment => 'patron_import.csv',
94     );
95     $csv->combine(@columnkeys);
96     print $csv->string, "\n";
97     exit 0;
98 }
99
100 my $uploadborrowers = $input->param('uploadborrowers');
101 my $matchpoint      = $input->param('matchpoint');
102 if ($matchpoint) {
103     $matchpoint =~ s/^patron_attribute_//;
104 }
105
106 #create a patronlist
107 my $createpatronlist = $input->param('createpatronlist') || 0;
108 my $dt = dt_from_string();
109 my $timestamp = $dt->ymd('-').' '.$dt->hms(':');
110 my $patronlistname = $uploadborrowers . ' (' . $timestamp .')';
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             session_id => scalar $input->cookie('CGISESSID'),
118             token  => scalar $input->param('csrf_token'),
119         });
120
121     my $handle   = $input->upload('uploadborrowers');
122     my %defaults = $input->Vars;
123
124     my $return = $Import->import_patrons(
125         {
126             file                         => $handle,
127             defaults                     => \%defaults,
128             matchpoint                   => $matchpoint,
129             overwrite_cardnumber         => $input->param('overwrite_cardnumber'),
130             preserve_extended_attributes => $input->param('ext_preserve') || 0,
131         }
132     );
133
134     my $feedback    = $return->{feedback};
135     my $errors      = $return->{errors};
136     my $imported    = $return->{imported};
137     my $overwritten = $return->{overwritten};
138     my $alreadyindb = $return->{already_in_db};
139     my $invalid     = $return->{invalid};
140
141     my $uploadinfo = $input->uploadInfo($uploadborrowers);
142     foreach ( keys %$uploadinfo ) {
143         push @$feedback, { feedback => 1, name => $_, value => $uploadinfo->{$_}, $_ => $uploadinfo->{$_} };
144     }
145
146     push @$feedback, { feedback => 1, name => 'filename', value => $uploadborrowers, filename => $uploadborrowers };
147
148     $template->param(
149         uploadborrowers => 1,
150         errors          => $errors,
151         feedback        => $feedback,
152         imported        => $imported,
153         overwritten     => $overwritten,
154         alreadyindb     => $alreadyindb,
155         invalid         => $invalid,
156         total           => $imported + $alreadyindb + $invalid + $overwritten,
157     );
158
159 }
160 else {
161     if ($extended) {
162         my @matchpoints = ();
163         my @attr_types = C4::Members::AttributeTypes::GetAttributeTypes( undef, 1 );
164         foreach my $type (@attr_types) {
165             my $attr_type = C4::Members::AttributeTypes->fetch( $type->{code} );
166             if ( $attr_type->unique_id() ) {
167                 push @matchpoints,
168                   { code => "patron_attribute_" . $attr_type->code(), description => $attr_type->description() };
169             }
170         }
171         $template->param( matchpoints => \@matchpoints );
172     }
173
174     $template->param(
175         csrf_token => Koha::Token->new->generate_csrf(
176             { session_id => scalar $input->cookie('CGISESSID'), }
177         ),
178     );
179
180 }
181
182 output_html_with_http_headers $input, $cookie, $template->output;
183